我有两个表:
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表中插入一行。
action
现在,我想查找执行了所有某些操作集的所有用户。像这样的东西:
SELECT user_id FROM user, action HAVING SET(action_type) INTERSECT (0,3,4,5) = (0,3,4,5);
但是,当然,我刚刚完成了最后一行。有没有在SQL中执行此操作的好方法?
这是组内查询的示例。我喜欢使用group by和来解决它们having,因为这是非常灵活的:
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;