聚合相当复杂的连接

时间:2013-09-26 05:08:44

标签: mysql join aggregate-functions

我有以下查询:我刚注意到它没有聚合用户的计数为0 item_count。我曾尝试调整此查询,因为我之前犯过这个错误,但不是这种更复杂的查询,我怎么需要调整它以便显示用户的item_count,即使0 ??

SELECT u.ID AS user_id,
                u.date_expired AS user_date_expired,
                u.first_name AS first_name,
                u.last_name AS last_name,
                COUNT(i.id)    AS item_count
FROM `user` `u`
LEFT JOIN `item` `i` ON i.recruiter_id = u.id
WHERE ((`u`.`id` IN ('15', '2', 13)) AND (i.date_added >
DATE_SUB(u.date_expired, INTERVAL  30 DAY)))
GROUP BY `u`.`id`

由于

强尼

1 个答案:

答案 0 :(得分:1)

以这种方式试试

SELECT u.id           AS user_id,
       u.date_expired AS user_date_expired,
       u.first_name   AS first_name,
       u.last_name    AS last_name,
       COUNT(*)       AS item_count
  FROM user u LEFT JOIN item i 
    ON i.recruiter_id = u.id
   AND i.date_added > u.date_expired - INTERVAL  30 DAY
 WHERE u.id IN (15, 2, 13) 
 GROUP BY u.id, u.date_expired, u.first_name, u.last_name