First I want to confirm this is even a sound and correct query.
Second I want to join in a way where even dates where no guests are attending shows up:
I want to get all screening dates where location = "Studio"
, There are 5 dates that have location Studio, so I expect 5 results. But I only get 4 because only 4 days have guests attending. How do I rewrite my query to show days where no guests are attending too (fifth row)
SCHEMA
screening_date_guest(guest_id, screening_date_id, attending)
user_guest_group(guest_id, user_id, group_id)
NOTES
Query
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`
My current RS looks like:
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
There should be another row:
5, 2015-05-22 00:00:00
I tried doing left joins, but still end up getting 4 rows.
I think you want a right join on the screening_dates table:
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`
If you want to get the fifth user who is not attending then you simply need to remove the attending column from your where condition ie, 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`
Try this
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`
This should give you all 5 days:
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'
I don't see why you need to include the user_guest_group table.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.