查找包含所有链接行的行
我有两个表:
User (id, name, etc)
UserRight (user_id, right_id)
我想找到拥有权限 1、2 和 3 的用户,但没有只拥有其中一两个权限的用户。此外,权限的数量也会有所不同,因此搜索 (1,2,3) 和 (1,2,3,4,5,6,7) 应该适用于大致相同的查询。
本质上:
SELECT *
FROM User
WHERE (
SELECT right_id
FROM tblUserRight
WHERE user_id = id
ORDER BY user_id ASC
) = (1,2,3)
这在 MySQL 中可能吗?
I've got two tables:
User (id, name, etc)
UserRight (user_id, right_id)
I want to find the users who have rights 1, 2 and 3, but no users who only have one or two of these. Also, the number of rights will vary, so searches for (1,2,3) and (1,2,3,4,5,6,7) should work with much the same query.
Essentially:
SELECT *
FROM User
WHERE (
SELECT right_id
FROM tblUserRight
WHERE user_id = id
ORDER BY user_id ASC
) = (1,2,3)
Is this possible in MySQL?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您还可以使用 PIVOT 来执行此操作,特别是如果您需要视觉表示。我在 SQL Server 上做了这个 - 你也许可以翻译它。
You can also do this using PIVOT, especially if you want a visual representation. I did this on SQL Server - you may be able to translate it.
与我的答案中指出的错误相对应,这里有一个带有计数和子查询的解决方案:
优化器当然可以将其更改为马丁·史密斯的解决方案(即通过使用分组依据)。
In correspondance with the errors in my answer pointed out, here a solution with count and a subquery:
An optimizer may of course change this to Martin Smith's solution (i.e. by using a group by).