查询没有显示0值mysql

时间:2015-12-06 16:10:51

标签: php mysql union zero

在我的查询中,我列出了不同客户的所有剧院门票销售和电影票销售。我遇到的问题是所有的' 0'门票销售,所以没有出现剧院门票或电影票的用户没有出现。

这是一张视觉方面的图片: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

2 个答案:

答案 0 :(得分:0)

inner join =>只有当你在两张桌子上都有记录时才能上线。

我认为您应该使用LEFT JOIN某处选择主表

http://dev.mysql.com/doc/refman/5.7/en/join.htmlhttp://dev.mysql.com/doc/refman/5.7/en/left-join-optimization.html

答案 1 :(得分:0)

我认为最后一个查询是您唯一想要的查询。 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上的条件是不必要的,因为joincase不匹配(注意:您可能需要检查客户列)。
  • order by 0是进行条件求和的标准方法(因此也是正确的)。但是,MySQL提供了一种更简单直观的语法。
  • 你的订单没有做任何事,因为它添加了两个字符串(因此相当于url。不要使用单引号永远作为列名,你不会有像这样的问题。