MySQL Join - 在另一个表上计数匹配

时间:2012-07-03 07:28:24

标签: mysql join

我有这个问题:

SELECT a.*, b.id AS host_id, COUNT(c.event_id) AS count_joins, COUNT(d.event_id) AS joined
FROM (`events` AS a)
INNER JOIN `users` AS b ON `b`.`id` = `a`.`host_id`
LEFT JOIN `joins` AS c ON `c`.`event_id` = `a`.`id`
LEFT JOIN `joins` AS d ON `d`.`event_id` = `a`.`id` AND d.user_id = 1
WHERE `a`.`date` > '1000-10-10 10:10:10'
GROUP BY `a`.`id`
ORDER BY `a`.`date` ASC
LIMIT 20

它获取所有事件,作者,连接数,并检查当前用户(id = 1)是否加入了该事件。

我遇到问题,如果用户加入了该事件,它将返回连接数,如果用户加入则返回1,否则返回0。

2 个答案:

答案 0 :(得分:0)

我认为问题在于你同时加入a,b,c和d。因此,每次任何人加入每个事件(a×c),然后 加入用户编号1记录时,您将获得一条记录((a×c) ×d)。因此,如果表格看起来像

事件:{e1,e2} 加入:{(e1,u1),(e1,u2),(e1,u3),(e2,u2),(e2,u4)}

您的查询(在聚合函数之前)返回

{(e1,u1,u1),(e1,u2,u1),(e1,u3,u1),(e2,u2,null),(e2,u4,null)}

你可能会得到你想要的东西

  • 在×c和上进行聚合,然后加入“joins as d”表
  • 在“c”上包含合成字段,例如c.user_id == 1 as is_user_1,然后在select子句中使用max( is_user_1 )

答案 1 :(得分:0)

试试这个:

SELECT a.*, b.id AS host_id, 
SUM(CASE WHEN c.event_id IS NOT NULL THEN 1 ELSE 0 END) AS count_joins, 
SUM(CASE WHEN c.event_id IS NOT NULL AND c.user_id = 1 THEN 1 ELSE 0 END) AS joined
FROM (`events` AS a)
INNER JOIN `users` AS b ON `b`.`id` = `a`.`host_id`
LEFT JOIN `joins` AS c ON `c`.`event_id` = `a`.`id`
WHERE `a`.`date` > '1000-10-10 10:10:10'
GROUP BY `a`.`id`
ORDER BY `a`.`date` ASC
LIMIT 20