2015-12-06 63 views
0

在我的查詢中,我列出了所有不同客戶的電影票銷售和電影票銷售額。我遇到的問題是所有'0'門票銷售,所以那些沒有加強劇院票或電影票的用戶沒有出現。查詢未顯示0值mysql

下面是視覺方面的一個畫面:table

我相信我需要做工會返回誰沒有買來的票的用戶。我似乎無法弄清楚這一點。

在此先感謝。

這裏是我到目前爲止的代碼:

select customer.hippcode, customer.LastName, customer.Firstname, customer.Email, 
count(ticketdetails.eventtype) as 'Theater Tickets', 
0 as 'Movie Tickets' 
from customer 
inner join ticketdetails on ticketdetails.hippcode = customer.hippcode 
where ticketdetails.hippcode is not null 
and ticketdetails.eventType ='T' 
Group by Customer.hippcode 
union 
select customer.hippcode, customer.LastName, customer.Firstname, customer.Email, 
0 as 'Theater Tickets', count(ticketdetails.eventtype) as 'Movie Tickets' 
from customer 
inner join ticketdetails on ticketdetails.hippcode = customer.hippcode 
where ticketdetails.hippcode is not null 
and ticketdetails.eventType ='M' 
Group by Customer.hippcode 
order by `theater tickets` + `movie tickets` desc; 
select 
    customer.hippcode, customer.LastName, customer.Firstname, customer.Email, 
    sum(case when ticketdetails.eventtype = 'T' then 1 else 0 end) as TheaterTickets, 
    sum(case when ticketdetails.eventtype = 'M' then 1 else 0 end) as MovieTickets 
from customer 
inner join ticketdetails on ticketdetails.hippcode = customer.hippcode 
where ticketdetails.hippcode is not null 
and ticketdetails.eventType in ('T', 'M') 
Group by customer.hippcode, customer.LastName, customer.Firstname, customer.Email 
Order by 'TheaterTickets' + 'MovieTickets' desc 
+1

我想你只需要一個'LEFT JOIN'而不是'INNER JOIN'。 –

回答

0

我認爲最後的查詢是你想要的唯一的一個。一個left join是合適的,但你必須要小心的where條款:

select c.hippcode, c.LastName, c.Firstname, c.Email, 
     sum(td.eventtype) as TheaterTickets, 
     sum(td.eventtype) as MovieTickets 
from customer c left join 
    ticketdetails td 
    on td.hippcode = c.hippcode and 
     td.eventType in ('T', 'M') 
Group by c.hippcode, c.LastName, c.Firstname, c.Email 
Order by count(t.hippcode) desc; 

注:

  • 表的別名使查詢更易於讀取和寫入。
  • 條件ticketdetails去在on條款,而不是where條款。
  • td.hippcode is not null上的條件是不必要的,因爲NULL將不匹配join(注意:您可能想要檢查客戶列)。
  • case是做條件總和(因此是正確的)的標準方式。但是,MySQL提供了一個更簡單直觀的語法。
  • 您的訂單是通過什麼都不做,因爲它增加了兩個字符串(因此相當於order by 0不要使用單引號不斷列名,你不會有這樣的問題。