问题描述
我正在使用MysqL 5.5 Command Line Client
。
我想要什么:
我上次尝试的时间:
SELECT e.event_id,e.title,e.description,e.event_date,e.image,sum(d.amount) as total,count(d.event_id) as total_donors FROM event e,donation d where d.event_id = e.event_id group by e.event_id;
这将联接表,但我也需要null值,如何修改此值以获取所需结果表的最后一行(在所附的图像中)?
此外,这种联接称为什么类型?
谢谢。
解决方法
您的查询只需要使用LEFT JOIN
进行转换,如下所示:
SELECT e.event_id,e.title,e.description,e.event_date,e.image,/*1*/
sum(ifnull(d.amount,0)) as total,count(d.event_id) as total_donors
FROM event e
/*2*/
LEFT JOIN donation d
/*3*/
ON d.event_id = e.event_id
group by e.event_id;
在上面的查询中观察以下标记:
/*1*/
在sum运算中加上ifnull
以返回0而不是null。如果sum的值之一为空,这还将防止空结果。
/*2*/
将逗号连接更改为LEFT JOIN
,特别是因为您希望显示左侧表中的所有行,尽管右侧表中没有匹配项。
/*3*/
将从where
更改为ON
。
这是一个小提琴演示:the docs about the rule targets