2

我有一个类似的表:

id    user_id    value
----------------------------
1     2          colour
2     2          receive_email
3     3          colour
4     3          receive_email
5     3          receive_info

我按 user_id 对该表进行分组。我想做的只是返回不包含值“receive_info”的组。因此,在上述情况下,我将返回一行,他的 user_id = 2。

我尝试了一些东西,这是最新的:

SELECT id, user_id, value  
FROM table 
GROUP BY user_id 
HAVING value NOT IN('receive_info');

我也试过:

SELECT id, user_id, value  
FROM table 
WHERE value NOT IN('receive_info') 
GROUP BY user_id;

当我这样做时,我会为确实包含值 = 'receive' 的用户取回记录。

任何人都看到我要去哪里错了吗?

谢谢

4

1 回答 1

7
SELECT  DISTINCT user_id
FROM    tableName a
WHERE   NOT EXISTS
        (
            SELECT  1
            FROM    tableName b
            WHERE   a.user_id = b.user_id AND
                    value = 'receive_info'
        )

或通过使用LEFT JOIN

SELECT  DISTINCT a.user_id
FROM    tableName a
        LEFT JOIN tableName b
            ON  a.user_id = b.user_id AND
                b.value = 'receive_info'
WHERE   b.user_id IS NULL

这两个查询将 OUTPUT

╔═════════╗
║ USER_ID ║
╠═════════╣
║       2 ║
╚═════════╝
于 2013-05-14T08:08:24.230 回答