从数据透视表中查找一行

时间:2015-12-14 09:21:01

标签: mysql sql

我有两个名为conversationsusers的表,它们与包含conversation_useruser_id列的数据透视表conversation_id绑定。

| conversation_id | user_id |
|-----------------|---------|
|               1 |       1 |
|               1 |       2 |
|               2 |       1 |
|               2 |       2 |
|               2 |       3 |

我想向数据库发送一些用户ID并检索它们在一起的对话。

例如:

当我发送12时,我必须收到conversation_id 1,当我发送123时我必须收到conversation_id 2

我怎么写这样的查询?

2 个答案:

答案 0 :(得分:3)

您可以使用GROUP BYHAVING

SELECT conversation_id 
FROM tab                     -- subquery/temp table/whatever
GROUP BY conversation_id 
HAVING SUM(user_id = 1) > 0
   AND SUM(user_id = 2) > 0
   AND SUM(user_id = 3) > 0
   AND SUM(user_id NOT IN (1,2,3)) = 0

SqlFiddleDemo

对于1和2:

SELECT conversation_id 
FROM tab
GROUP BY conversation_id 
HAVING SUM(user_id = 1) > 0
   AND SUM(user_id = 2) > 0
   AND SUM(user_id NOT IN (1,2)) = 0

答案 1 :(得分:0)

Group_concat可用于根据您的要求检索结果。您可以相应地更改having子句条件:试试这个让我知道

SELECT conversion_id 
FROM (
    SELECT 
    conversion_id, 
    group_concat(user_id, ',')
    FROM conversions
    HAVING group_concat(user_id, ',') = '1,2,3' 
    GROUP BY conversion_id
)