首先,我想确认这是一个合理而正确的查询 其次,我想加入一个甚至没有客人参加的日期的方式:
我希望所有筛选日期都在location = "Studio"
,有5个日期有位置Studio,所以我希望有5个结果。但我只得到4,因为只有4天有客人参加。如何重写我的查询以显示没有客人参加的日子(第五行)
SCHEMA
screening_date_guest(guest_id, screening_date_id, attending)
user_guest_group(guest_id, user_id, group_id)
备注
查询
select
count(distinct(sdg.guest_id)),
`date`
from
screening_date_guest sdg
inner join
user_guest_group ugs on ugs.guest_id = sdg.guest_id
inner join
screening_dates sd on sd.id = sdg.screening_date_id
where
attending = 1
AND
sd.location = 'Studio'
group by
`date`
order by sd.`date`
我当前的RS看起来像:
15, 2015-05-18 00:00:00
4, 2015-05-19 00:00:00
2, 2015-05-20 00:00:00
4, 2015-05-21 00:00:00
应该有另一行:
5, 2015-05-22 00:00:00
我尝试过做左连接,但最终仍然得到4行。
答案 0 :(得分:0)
我想你想在screening_dates表上进行正确的加入:
http://www.w3schools.com/sql/sql_join_right.asp
select
count(distinct(sdg.guest_id)),
`date`
from
screening_date_guest sdg
inner join
user_guest_group ugs on ugs.guest_id = sdg.guest_id
right join
screening_dates sd on sd.id = sdg.screening_date_id
where
attending = 1
AND
sd.location = 'Studio'
group by
`date`
order by sd.`date`
答案 1 :(得分:0)
如果您想要获得第五位未参加的用户,您只需要从您所在的条件中删除参加列,即attending = 1
select
count(distinct(sdg.guest_id)),
`date`
from
screening_date_guest sdg
inner join
user_guest_group ugs on ugs.guest_id = sdg.guest_id
inner join
screening_dates sd on sd.id = sdg.screening_date_id
where
sd.location = 'Studio'
group by
`date`
order by sd.`date`
答案 2 :(得分:0)
试试这个
select case when attending = 1
then count(distinct(sdg.guest_id))
else
'0'
end ,
`date`
from
screening_date_guest sdg
inner join
user_guest_group ugs on ugs.guest_id = sdg.guest_id
inner join
screening_dates sd on sd.id = sdg.screening_date_id
where
sd.location = 'Studio'
group by
`date`,attending
order by sd.`date`
答案 3 :(得分:0)
这应该给你5天时间:
select
count(distinct(sdg.guest_id)),
sd.'date'
from
screening_dates sd
left join
screening_date_guest sdg
on sdg.screening_date_id = sd.id
and sdg.attending = 1
where sd.location = 'Studio'
我不明白为什么需要包含user_guest_group表。