SQL 查询连接中的所有记录都匹配某个条件吗?
我有一个看似简单的问题,但无法通过 SQL 找出正确的解决方案。我专门使用postgresql。
采取以下措施:
SELECT *
FROM users INNER JOIN tags
ON (tags.user_id = users.id)
WHERE tags.name IN ('word1', 'word2')
这不能满足我的需要。我想找到标签仅包含在列表中的用户。如果用户的标签不在列表中,则不应包含该用户。
“user1”标签:word1、word2、word3
“user2”标签:word1
'user3' 标签:word1、word2
给定:word1 和 word2。我想准备一个返回“user2”和“user3”的查询。 “user1”被排除,因为它具有不在列表中的标签。
希望我说清楚了。感谢您的帮助!
I have what seems to be a simple problem, but can not figure out the proper solution via SQL. I'm using postgresql specifically.
Take the following:
SELECT *
FROM users INNER JOIN tags
ON (tags.user_id = users.id)
WHERE tags.name IN ('word1', 'word2')
This does not do what I need. I want to find users whose tags are ONLY included in the list. If the user has a tag that is not in the list, the user should not be included.
'user1' tags: word1, word2, word3
'user2' tags: word1
'user3' tags: word1, word2
Given: word1 and word2. I want to prepare a query that returns 'user2' and 'user3'. 'user1' is excluded because it has a tag that is not in the list.
Hopefully I made this clear. Thanks for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
依赖 COUNT(*) = 2 将要求标签表中的 user_id 和 name 不能重复。如果是这样的话,我就会走那条路。否则,这应该有效:
Relying on COUNT(*) = 2 will require that there can be no duplicates of user_id and name in the tags table. If that's the case, I'd go that route. Otherwise, this should work:
要获取没有列表中未包含的标签的所有用户,请使用下面的查询。返回的用户可能没有标签或只有一个与单词匹配的标签,但我知道这是所需的功能。
To get all users that don't have a tag that is not in the list, use the query below. Could be that users are returned that have no tag or only one tag matching the words, but I understand that is the desired functionality.
或者
or