0

I have this query:

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

It gets all events, the author, the number of joins and check if the current user (id = 1) joined the event.

I'm having problem checking if the user joined the event, it's returning the number of joins, not 1 if the user joined or 0 if not.

4

2 回答 2

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
于 2012-07-03T08:46:50.443 回答
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) }

你可能会得到你所追求的

  • 在 a × c 上进行聚合,然后加入“joins as d”表
  • 例如,在“c”上包括一个合成字段,c.user_id == 1 as is_user_1然后采用max( is_user_1 )select 子句
于 2012-07-03T07:45:34.283 回答