2015-04-15 33 views
0

首先我要確認這是一個完善且正確的查詢。
其次,我想在某種程度上,甚至在沒有客人蔘加演出了日期加盟:查詢以獲取所有參加日期的訪客

我想所有篩選日期,其中location = "Studio",有跡象表明,有位置工作室5個日期,所以我希望5個結果。但我只得到4,因爲只有4天有賓客參加。如何重寫我的查詢,以顯示在沒有客人蔘加過(第五行)

SCHEMA

screening_date_guest(guest_id, screening_date_id, attending) 
user_guest_group(guest_id, user_id, group_id) 

注意

  • 客人只能屬於一個GROUP_ID天但多個user_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

如果您在[SQL FIDDLE](http://sqlfiddle.com/) – 1000111

回答

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` 
+0

中提供了一個正在運行的問題示例,那麼發現問題總是比較容易,但最好是添加代碼而不是鏈接 –

+0

謝謝Asieh,good call 。 – louieoc

0

如果你想要得到誰不參加,那麼你只需要簡單地從去除主治列第五用戶你的where條件即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` 
+0

我真的想獲得所有5個日期,因爲這是填充日曆。必須有辦法顯示我感覺的所有日子和他們的客人數量。請幫忙。 – vick

+0

約有25位客人蔘加4天,但第5天有0位客人。 – vick

+0

@vick: - 這很難理解,如果第5天沒有客人蔘加那麼你期待什麼? –

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` 
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表。

+0

我需要爲其他目的 – vick

相關問題