我有两张桌子:
CREATE TABLE user (
user_id INT PRIMARY KEY,
...
);
CREATE TABLE action (
action_id INT PRIMARY KEY,
user_id INT FOREIGN KEY REFERENCES user(user_id),
action_type TINYINT,
...
);
每次用户执行特定操作时,都会在action
表中插入一行。
现在,我想查找已执行所有操作集的所有用户。像这样:
SELECT user_id
FROM user, action
HAVING SET(action_type) INTERSECT (0,3,4,5) = (0,3,4,5);
但当然我刚刚编写了最后一行。有没有一种在SQL中执行此操作的好方法?
答案 0 :(得分:3)
这是set-within-sets查询的示例。我喜欢使用group by
和having
来解决它们,因为这是非常灵活的:
SELECT user_id
FROM action a
WHERE action_type IN (0, 3, 4, 5)
GROUP BY user_id
HAVING COUNT(DISTINCT action_type) = 4;
答案 1 :(得分:1)
4
是你集合中的动作数量
SELECT u.user_id
FROM user u
JOIN action a on u.user_id = a.user_id
WHERE action_type IN (0,3,4,5)
GROUP BY u.user_id
HAVING count(distinct a.action_type) = 4
另一种方式是
SELECT u.user_id
FROM user u
JOIN action a on u.user_id = a.user_id
GROUP BY u.user_id
HAVING sum(a.action_type = 0) > 0
AND sum(a.action_type = 3) > 0
AND sum(a.action_type = 4) > 0
AND sum(a.action_type = 5) > 0