INNER JOIN不返回任何行

时间:2015-04-04 23:48:11

标签: mysql inner-join

我正试图从2015年4月没有任何活动的数据库中获取客户名称:

SELECT customer.customerId, customer.Name, event.Date
FROM customer
INNER JOIN event ON event.customerId=customer.customerId
INNER JOIN 
    (
    SELECT eventId AS evid, customerId
    FROM  event
    WHERE year(event.Date)=2015 AND month(event.Date)=04
    GROUP BY customerId
    )
EV ON event.eventId = EV.evid
WHERE event.customerId IS NULL

我得到零行,我应该有约。那里有20个客户。查询出了什么问题?

2 个答案:

答案 0 :(得分:1)

您应该使用左连接,并且只需要加入表格一次。但是,您无法选择活动日期,因为您将获得客户,而不会在该时间间隔内发生任何事件:

select
  customer.customerId, customer.Name
from
  customer
  left join event on event.customerId = customer.customerId
    and year(event.Date) = 2015 and month(event.Date) = 4
where
  event.customerId is null

答案 1 :(得分:1)

这应该为您提供2015年4月没有任何活动的所有客户的客户ID和姓名:

SELECT customer.customerId, customer.Name
FROM customer
WHERE customerId NOT IN
(
    SELECT customerId
    FROM  event
    WHERE year(event.Date)=2015 AND month(event.Date)=04
) EV;