gpt4 book ai didi

mysql - 即使 count(row) 为零,如何从表中获取数据?请查看描述以了解更多详细信息和查询?

转载 作者:行者123 更新时间:2023-11-29 18:38:42 25 4
gpt4 key购买 nike

表一

id   mandal_name1    mandal12    mandal23    mandal3

table address

id   mandal_name   date1    mandal1       2017-07-11 12:34:112    mandal1       2017-07-11 12:54:453    mandal1      2017-07-11 12:23:23
SELECT count(id) as yesterday_count, mandal FROM address WHERE date(date) = '2017-07-11'

结果一目了然

3 , mandal1

期待结果

3 , mandal10 , mandal20 , mandal3...

最佳答案

在这种情况下,关键是使用OUTER JOIN - LEFT JOIN

你可以这样做

SELECT m.mandal_name, COUNT(a.id) AS yesterday_count
FROM table_one m LEFT JOIN address a
ON m.mandal_name = a.mandal_name
AND a.date >= '2017-07-11'
AND a.date < '2017-07-12'
GROUP BY m.mandal_name;

SELECT m.mandal_name, COALESCE(count, 0) AS yesterday_count
FROM table_one m LEFT JOIN (
SELECT mandal_name, COUNT(*) AS count
FROM address
WHERE date >= '2017-07-11'
AND date < '2017-07-12'
) a
ON m.mandal_name = a.mandal_name;

这是一个SQLFiddle演示

输出

| mandal_name | yesterday_count ||-------------|-----------------||     mandal1 |               3 ||     mandal2 |               0 ||     mandal3 |               0 |

进一步阅读 - A Visual Explanation of SQL Joins

顺便说一句 - 不要使用DATE(date),因为它使得无法在date列上使用索引,从而有效地导致全表扫描。

关于mysql - 即使 count(row) 为零,如何从表中获取数据?请查看描述以了解更多详细信息和查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45071280/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com