我有一张类似于:
的表格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'的用户的记录。
任何人都知道我哪里出错了?
由于
答案 0 :(得分:6)
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
两个查询将输出
╔═════════╗
║ USER_ID ║
╠═════════╣
║ 2 ║
╚═════════╝