MySQL - 选择具有覆盖集合值的组

时间:2015-08-06 15:43:05

标签: mysql sql set

我有两张桌子:

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中执行此操作的好方法?

2 个答案:

答案 0 :(得分:3)

这是set-within-sets查询的示例。我喜欢使用group byhaving来解决它们,因为这是非常灵活的:

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)

`having子句中的

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