SQL Server:连接两个表,其中左表包含每个标识符中右表的所有行

问题描述 投票:0回答:1

我正在尝试匹配两个表,其中左表必须包含其每个块中的所有右表行!

好吧,如果没有例子,我就无法更好地描述它:

左表包含多个行块,其中每个块包含7行,列标题在每个块中具有不同的值,每个块由数字标识,如下表所示:

表格1:

objectID    propertyID      title
------------------------------------
0           17020           Iphone
0           17021           7 plus
0           17022           retina
0           17023           2 GB
0           17024           1960 mh
0           17025           64 GB
0           17026           gold

1           17020           Iphone
1           17021           7 plus
1           17022           retina
1           17023           2 GB
1           17024           1960 mh
1           17025           64 GB
1           17026           white

2           17020           Iphone
2           17021           7 plus
2           17022           retina
2           17023           2 GB
2           17024           1960 mh
2           17025           128 GB
2           17026           white

3           17020           Iphone
3           17021           7
3           17022           retina
3           17023           3 GB
3           17024           1960 mh
3           17025           128 GB
3           17026           red

并且有第二个表总共有3行。

表2:

id      title       propertyID
-----------------------------
1001    7 plus      17021
1002    2 GB        17023
1003    64 GB       17025

现在我想在table1的每个块中匹配table2的标题?再次,很难解释!

期望的结果:

objectID    propertyID     title
----------------------------------
0           17021           7 plus
0           17023           2 GB
0           17025           64 GB
1           17021           7 plus
1           17023           2 GB
1           17025           64 GB

请注意,只有table1的前两个块包含table2中找到的所有三个标题。我想要一个查询来比较table2的三行到table1的每个块,而不仅仅是逐行比较。

因此,如果我想知道涉及哪个'objectID',那么答案就是

objectID
--------
0
1

问题来自我使用以下查询实际加入这两个表:

select t1.objectID, t1.propertyID, t1.title
from table1 t1
inner join table2 t2 on t2.title = t1.title

目前的结果:

objectID    propertyID      title
----------------------------------
0           17021           7 plus
0           17023           2 GB
0           17025           64 GB
1           17021           7 plus
1           17023           2 GB
1           17025           64 GB
2           17021           7 plus
2           17023           2 GB

这里查询找到包含2个table2标题的table1的块号2! 但它必须在每个块中找到所有三行table2。

我甚至要加入两张桌子吗?我怎样才能得到理想的结果?

sql sql-server
1个回答
3
投票

您可以通过group by和having子句来实现

select t1.objectID, t1.propertyID, t1.title
from table1 t1
inner join table2 t2 on t2.title = t1.title
group by t1.objectID, t1.propertyID, t1.title
having count(*) = (Select count(*) FROM table2)
© www.soinside.com 2019 - 2024. All rights reserved.