SQL n:n 连接多行
SQL n:n join over multiple rows
我有一辆车 table 列出了各种属性,我有一辆 property_group table 将各种属性组合成不同的组。
现在我想知道哪些汽车完全适合哪些 property_groups。
汽车名称唯一,这将是一个简单的连接 - 但汽车名称重复 ???
汽车table
id
name
property
1
ford
1
2
ford
2
3
nissan
1
4
nissan
3
5
nissan
5
property_group 表格
id
group
property
1
r01
1
2
r0l
2
3
ks99
1
4
ks99
3
5
ks99
5
6
uv55
1
7
uv55
2
8
uv55
3
9
uv55
4
0
uv55
5
预期结果:
name
group
ford
r01
ford
uv55
nissan
ks99
nissan
uv55
嗯。 . .您可以在属性上使用 join
,然后计算该组汽车之间有多少属性匹配:
select c.name, pg.group
from car c join
(select pg.*,
count(*) over (partition by group) as num_properties
from property_group pg
) pg
on pg.property = c.property
group by c.name, pg.group, pg.num_properties
having count(*) = pg.num_properties;
请注意,group
是一个非常糟糕的列名称,因为它是一个 SQL 关键字。
Here 是一个 db<>fiddle.
我有一辆车 table 列出了各种属性,我有一辆 property_group table 将各种属性组合成不同的组。
现在我想知道哪些汽车完全适合哪些 property_groups。
汽车名称唯一,这将是一个简单的连接 - 但汽车名称重复 ???
汽车table
id | name | property |
---|---|---|
1 | ford | 1 |
2 | ford | 2 |
3 | nissan | 1 |
4 | nissan | 3 |
5 | nissan | 5 |
property_group 表格
id | group | property |
---|---|---|
1 | r01 | 1 |
2 | r0l | 2 |
3 | ks99 | 1 |
4 | ks99 | 3 |
5 | ks99 | 5 |
6 | uv55 | 1 |
7 | uv55 | 2 |
8 | uv55 | 3 |
9 | uv55 | 4 |
0 | uv55 | 5 |
预期结果:
name | group |
---|---|
ford | r01 |
ford | uv55 |
nissan | ks99 |
nissan | uv55 |
嗯。 . .您可以在属性上使用 join
,然后计算该组汽车之间有多少属性匹配:
select c.name, pg.group
from car c join
(select pg.*,
count(*) over (partition by group) as num_properties
from property_group pg
) pg
on pg.property = c.property
group by c.name, pg.group, pg.num_properties
having count(*) = pg.num_properties;
请注意,group
是一个非常糟糕的列名称,因为它是一个 SQL 关键字。
Here 是一个 db<>fiddle.