SQL查询,它提供与多个列匹配的不同结果 [英] SQL query that gives distinct results that match multiple columns
本文介绍了SQL查询,它提供与多个列匹配的不同结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
很抱歉,我无法为我的问题提供更好的标题,因为我是SQL的新手。
我正在寻找解决以下问题的SQL查询字符串。
Sorry, I couldn't provide a better title for my problem as I am quite new to SQL. I am looking for a SQL query string that solves the below problem.
让我们假设下面的表:
DOCUMENT_ID | TAG
----------------------------
1 | tag1
1 | tag2
1 | tag3
2 | tag2
3 | tag1
3 | tag2
4 | tag1
5 | tag3
现在我想选择所有包含一个或多个标签的不同的文档ID(但是必须提供所有指定的标签)。
例如:
选择所有带tag1的document_id,tag2将返回1和3(但不是4,因为它没有tag2)。
Now I want to select all distinct document id's that contain one or more tags (but those must provide all specified tags). For example: Select all document_id's with tag1 and tag2 would return 1 and 3 (but not 4 for example as it doesn't have tag2).
这是最好的方法是什么?
What would be the best way to do that?
尊敬的,
Kai
Regards, Kai
推荐答案
SELECT document_id
FROM table
WHERE tag = 'tag1' OR tag = 'tag2'
GROUP BY document_id
HAVING COUNT(DISTINCT tag) = 2
编辑:
由于缺乏约束而更新...
Updated for lack of constraints...
这篇关于SQL查询,它提供与多个列匹配的不同结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文