【问题标题】:How to full join the two tables with the null values as well?如何用空值完全连接两个表?
【发布时间】:2021-02-04 01:45:35
【问题描述】:

我正在使用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;

这加入了表格,但我也想要空值,如何修改它以获取所需结果表中的最后一行(在附图中)?

另外,这种类型的连接叫什么?

谢谢。

【问题讨论】:

标签: mysql join outer-join sql-null


【解决方案1】:

您的查询只需要像这样使用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

这是一个小提琴演示:https://dbfiddle.uk/?rdbms=mysql_5.5&fiddle=723cc34b7b875111701d9134b443f39b

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-14
    • 2021-05-08
    • 2015-06-19
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    • 1970-01-01
    相关资源
    最近更新 更多