mysql查询结果未显示某些行
我对如何查询下表感到困惑。我只想显示在特定日期订购和接收的数量 日历表mysql查询结果未显示某些行,mysql,Mysql,我对如何查询下表感到困惑。我只想显示在特定日期订购和接收的数量 日历表 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 电话号码详情表 id | dateOrdered | dateReceived | upg 1 | 2013-07-01
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
电话号码详情表
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 |
请提供一些指导。非常感谢。我认为您的加入不正确,因为您应该使用on而不是where:
from `phone_details` JOIN calendar
where calendar.date = phone_details.dateOrdered
尝试使用:
from `phone_details` JOIN calendar
on calendar.date = phone_details.dateOrdered
您需要一个
左联接
来为日历
中的每一行生成结果,即使它们与您的电话\u详细信息
表中的任何内容都不匹配
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;
这个很好用。
您可以在此处检查加入,以及添加OP想要但未包含在查询中的附加列。非常感谢,这非常有效,我在发布此处之前尝试了左加入,我想我得到了日期条件颠倒,这就是为什么它第一次不起作用的原因。再次感谢
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(id) FROM phone_details
WHERE dateReceived = calendar.date
)AS `received`
from `phone_details` JOIN calendar
ON calendar.date = phone_details.dateOrdered or calendar.date = phone_details.dateReceived
group by calendar.date DESC