选择所有项目并按条件计数在相关表中

时间:2019-01-31 13:52:31

标签: mysql sql

我的匹配和反应表如下:

REACTION
+----------+----------+----------+----------+
| user_id  | game_id  | item_id  | reaction |
+----------+----------+----------+----------+
|        1 |    1     |     1    |     1    |
|        1 |    1     |     2    |     1    |
|        2 |    1     |     1    |     1    |
|        2 |    1     |     2    |     0    |
+----------+----------+----------+----------+
MATCH:
+----------+----------+
| game_id  | item_id  |
+----------+----------+
|        1 |    1     |
|        1 |    2     |
+----------+----------+

现在,我想(如果可能,没有子查询)从MATCH表中选择所有item_id,并为id = 2的用户选择表Reaction中的field reaction等于1的行数。例如,对于已定义的表,我想获取以下结果:

+----------+----------+
|  item_id | count    |
+----------+----------+
|     1    |    1     |
|     2    |    0     |
+----------+----------+

我尝试过类似的事情

SELECT match.item_id, COUNT(reaction.user_id) as c
FROM match 
LEFT JOIN reaction ON reaction.item_id = match.item_id 
WHERE reaction.reaction = 1 AND match.game_id = 2
GROUP BY match.item_id
HAVING c > 0

但是它没有按预期工作。我无法获得特定用户的计数。

3 个答案:

答案 0 :(得分:1)

我认为你很亲密。我认为您只需要将第二个表上的条件移至ON子句:

SELECT m.item_id, COUNT(r.user_id) as c
FROM match m LEFT JOIN
     reaction r
     ON r.item_id = m.item_id AND
        r.reaction = 1 AND
        r.user_id = 2
WHERE m.game_id = 2
GROUP BY m.item_id;

我不确定HAVING子句的用途,因为您似乎想要计数0

请注意,这还引入了表别名,因此查询更易于编写和阅读。

答案 1 :(得分:0)

SELECT match.item_id, COUNT(reaction.user_id) as c
FROM match JOIN reaction ON (reaction.item_id = match.item_id and reaction.reaction = 1 AND match.game_id = 2)
GROUP BY match.item_id
HAVING COUNT(reaction.user_id)

我认为您需要过滤“加入之前”->,因此请使用“ on”子句。 在建立连接后之后应用where中的过滤器,而在建立连接前 之前应用在on子句中应用的过滤器

答案 2 :(得分:0)

您还没有game_id = 2,因此应该不返回任何值
并且您不应该在其中将wprk用作内部连接的条件下使用左连接表列,在这种情况下,应在ON子句

中移动相关条件
SELECT match.item_id, COUNT(reaction.user_id) as c
FROM match 
LEFT JOIN reaction ON reaction.item_id = match.item_id  
    AND reaction.reaction = 1 
WHERE  match.game_id = 2
GROUP BY match.item_id
HAVING c > 0

但也可以尝试

SELECT match.item_id, COUNT(reaction.user_id) as c
FROM match 
LEFT JOIN reaction ON reaction.item_id = match.item_id  
    AND reaction.reaction = 1 

GROUP BY match.item_id