gpt4 book ai didi

mysql 查询结果不显示某些行

转载 作者:行者123 更新时间:2023-11-29 05:28:17 24 4
gpt4 key购买 nike

我对如何查询下表感到困惑。我只是想显示在特定日期订购和收到的数量。

日历表

id  |  date
1 | 2013-07-01
2 | 2013-07-02
3 | 2013-07-03
4 | 2013-07-04
5 | 2013-07-05
6 | 2013-07-06
7 | 2013-07-07

phone_details 表

id   |  dateOrdered    | dateReceived | upg
1 | 2013-07-01 | 2013-07-05 | exp
2 | 2013-07-02 | 2013-07-05 | post
3 | 2013-07-02 | 2013-07-06 | upgrade
4 | 2013-07-07 | 2013-07-07 | upggrade
5 | 2013-07-03 | 2013-07-04 | exp
6 | 2013-07-01 | 2013-07-02 | exp

我希望的结果是什么。

calendar.date  | noOrdered   |  noReceived  | # of post  | # of exp  | # of upgrade
2013-07-01 | 2 | | | 2 |
2013-07-02 | 2 | 1 | 1 | | 1
2013-07-03 | 1 | | | 1 |
2013-07-04 | | 1 | | |
2013-07-05 | | 2 | | |
2013-07-06 | | 1 | | |
2013-07-07 | 1 | 1 | | 1 |

这是我的查询:

select calendar.date,DAYNAME(calendar.date) as `day`,
sum(if((`phone_details`.`upg` = 'Post'),1,0)) AS `Post Paid`,
sum(if((`phone_details`.`upg` = 'Upgrade'),1,0)) AS `Upgrade`,
sum(if(((`phone_details`.`upg` = 'Exp') or (`phone_details`.`upg` = 'Future Exp')),1,0)) AS `Exp`,
(select count(phone_ID) FROM phone_details
WHERE dateReceived = calendar.date
)AS `received`

from `phone_details` JOIN calendar
where calendar.date = phone_details.dateOrdered

group by calendar.date DESC

此查询的问题是,如果某个日期没有任何订单,它不会在结果中显示它,因此即使在该日期有一个接收,它仍然不会显示。我的结果看起来就像下表而不是上表。如果我对每一列进行子查询,我能够产生我想要的结果,但处理时间似乎会大大减慢。

calendar.date  | noOrdered   |  noReceived  | # of post  | # of exp  | # of upgrade
2013-07-01 | 2 | | | 2 |
2013-07-02 | 2 | 1 | 1 | | 1
2013-07-03 | 1 | | | 1 |
2013-07-07 | 1 | 1 | | 1 |

一些指导将不胜感激。非常感谢。

最佳答案

您需要一个 LEFT JOINcalendar 中的每一行生成结果,即使它们与您的 phone_details 中的任何内容都不匹配表格;

SELECT c.date "calendar_date", 
SUM(c.date=pd.dateOrdered) noOrdered,
SUM(c.date=pd.dateReceived) noReceived,
SUM(c.date=pd.dateOrdered AND upg='post') "# of post",
SUM(c.date=pd.dateOrdered AND upg='exp') "# of exp",
SUM(c.date=pd.dateOrdered AND upg='upgrade') "# of upgrade"
FROM calendar c
LEFT JOIN phone_details pd
ON c.date = pd.dateOrdered
OR c.date = pd.dateReceived
GROUP BY c.date;

An SQLfiddle to test with .

关于mysql 查询结果不显示某些行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17500634/

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