我正在使用一个简单的存储过程从两个表中收集数据并发送回PHP:
BEGIN
DECLARE cur_name VARCHAR(50);
SELECT currency_name INTO cur_name FROM currencies WHERE id = currency_id_var;
SELECT cur_name, sum(amount) AS income_amount, currency_id, month(income_date) AS month_of_income
FROM incomes
WHERE user_id = user_id_var
AND currency_id = currency_id_var
AND income_date > year_beginning_var
AND month(income_date) = month_var
GROUP BY currency_id;
END
它的工作正常,除非在'收入'表中找不到记录。我需要来自程序的响应,其中'cur_name'设置(它总是有一些值),其余变量(income_amount,currency_id,month_of_income)设置为NULL。 我问的是一些无法做到的事情吗? 我试图使它与 SELECT IFNULL 和 UNION SELECT NULL 类命令一起工作,但没有成功...... 谢谢!
答案 0 :(得分:0)
您可以将两个查询合并到LEFT JOIN
中,如下所示:
SELECT currency_name as cur_name,
income_amount,
currency_id,
month_of_income
FROM currencies
LEFT JOIN
(
SELECT cur_name, sum(amount) AS income_amount, currency_id, month(income_date) AS month_of_income
FROM incomes
WHERE user_id = user_id_var
AND currency_id = currency_id_var
AND income_date > year_beginning_var
AND month(income_date) = month_var
GROUP BY currency_id;
)
ON currency_id = currencies.id
WHERE currencies.id = currency_id_var;
未经测试,但您明白了:它是LEFT JOIN
,因此保证为左表(currencies
)中的每个匹配行返回至少一行,如果是右表(子查询)不会产生任何结果,相应的字段将返回为NULL
。
为了更好的可读性,我会考虑将子查询移动到视图,然后左键连接。