繁体   English   中英

SQL Server 2014:仅选择与另一个表中的所有行匹配的行

[英]SQL Server 2014: SELECT only those rows that match all rows in another table

我是SQL Server的初学者。 我试图解决这个问题:

从“ItemTag”表中选择所有(不同)“item_id”,其对应的“tag_id”值与“UserTagList”表中的至少“all”值匹配。

我在下面尝试了一个连接,但是我得到的查询结果应该返回item_id 5,因为它有tag_id的3和4。

非常感谢任何帮助。

下面是SQL架构

SQL小提琴

SQL Server 2014架构设置:

CREATE TABLE UserTagList (id INT);

INSERT INTO UserTagList (id) 
VALUES (3), (4);

CREATE TABLE ItemTag (id INT, item_id INT, tag_id INT);

INSERT INTO ItemTag (id, item_id, tag_id)
VALUES (1, 5, 3), (2, 5, 4), (3, 5, 6), (4, 6, 3), (5, 7, 4);

查询1

SELECT i.item_id, i.tag_id 
FROM ItemTag AS i 
JOIN UserTagList AS u ON i.tag_id = u.id

结果

| item_id | tag_id |
|---------|--------|
|       5 |      3 |
|       5 |      4 |
|       6 |      3 |
|       7 |      4 |

这是一个查询,其中group byhaving非常有用:

select i.item_id
from ItemTag i join
     UserTagList u 
     on i.tag_id = u.id
group by i.item_id
having count(*) = (select count(*) from UserTagList);

我会在这里使用聚合的左连接:

SELECT t1.item_id
FROM ItemTag t1
LEFT JOIN UserTagList t2
    ON t1.tag_id = t2.id
GROUP BY t1.item_id
HAVING SUM(CASE WHEN t2.id IS NULL THEN 1 ELSE 0 END) = 0

这里的逻辑是,如果对于给定的item_id组,其一个或多个标签与UserTagList表中的任何内容不匹配,则HAVING子句中的总和将检测并计算空和非匹配记录。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM