如何查询 sql 服务器中具有多对多关系的 2 个表以识别差异
How to query 2 tables in sql server with many to many relationship to identify differences
我有两个具有多对多关系的 table,我正在尝试将 2 个 table 合并到一个 select 语句中。我想查看来自两个 tables 的所有记录,但只匹配来自 table A 的 1 条记录到 table b 的 1 条记录,所以空值是可以的。
例如tableA有20条记录只匹配到tableB的15条记录,我想查看全部20条记录,匹配不到的5条可以显示为null。
Table 1
有点事 |代码#
苹果 | 75
披萨 | 75
橙色 | 6
球 | 75
绿色 | 4
红色 | 6
Table 2
日期 | id#
2 月 15 日 | 75
2 月 11 日 | 75
1 月 10 日 | 6
08 年 4 月 | 4
我需要的结果是
有点事 |日期 |代码# |编号
苹果 | 2 月 15 日 | 75 | 75
披萨 | 2 月 11 日 | 75 | 75
橙色 | 1 月 10 日 | 6 | 6
球 |空 | 75 |空
绿色 | 08 年 4 月 | 4 | 4
红色 |空 | 6 |空
常规的 Left-join 应该可以为您完成。
select tableA.*
, tableB.*
from tableA
left join tableB
on tableB.PrimaryKey = tableA.PrimaryKey
左外连接
问题已更改
使它成为一个完整的外部连接
select table1.*, table2.*
from table1
full outer join table2
on table1.Code# = table2.id#
这可能不是真正的多对多,但我认为这就是您所要求的
我们需要查看 table 结构才能确定地告诉您,但本质上您加入了完整的密钥(如果可能的话)
SELECT * FROM TABLEA A
JOIN TABLEB B ON
A.FULLKEY = B.FULLKEY
我正在想象这样的事情。你想并排成对的行,但一侧会比其他的多。
select * /* change to whatever you need */
from
(
select *, row_number() over (partition by "code#" order by "something") as rn
from tableA
) as a
full outer join /* sounds like maybe left outer join will work too */
(
select *, row_number() over (partition by "id#" order by "date" desc) as rn
from tableB
) as b
on b."id#" = a."code#" and b.rn = a.rn
实际上,我不知道您如何在 "apple" 和 "pizza" 之后得到 "ball" 而没有其他列进行排序。 SQL 表中的行没有任何排序,您不能依赖 select *...
中的默认列表或假设插入顺序很重要。
我有两个具有多对多关系的 table,我正在尝试将 2 个 table 合并到一个 select 语句中。我想查看来自两个 tables 的所有记录,但只匹配来自 table A 的 1 条记录到 table b 的 1 条记录,所以空值是可以的。
例如tableA有20条记录只匹配到tableB的15条记录,我想查看全部20条记录,匹配不到的5条可以显示为null。
Table 1
有点事 |代码#
苹果 | 75
披萨 | 75
橙色 | 6
球 | 75
绿色 | 4
红色 | 6
Table 2
日期 | id#
2 月 15 日 | 75
2 月 11 日 | 75
1 月 10 日 | 6
08 年 4 月 | 4
我需要的结果是
有点事 |日期 |代码# |编号
苹果 | 2 月 15 日 | 75 | 75
披萨 | 2 月 11 日 | 75 | 75
橙色 | 1 月 10 日 | 6 | 6
球 |空 | 75 |空
绿色 | 08 年 4 月 | 4 | 4
红色 |空 | 6 |空
常规的 Left-join 应该可以为您完成。
select tableA.*
, tableB.*
from tableA
left join tableB
on tableB.PrimaryKey = tableA.PrimaryKey
左外连接
问题已更改
使它成为一个完整的外部连接
select table1.*, table2.*
from table1
full outer join table2
on table1.Code# = table2.id#
这可能不是真正的多对多,但我认为这就是您所要求的
我们需要查看 table 结构才能确定地告诉您,但本质上您加入了完整的密钥(如果可能的话)
SELECT * FROM TABLEA A
JOIN TABLEB B ON
A.FULLKEY = B.FULLKEY
我正在想象这样的事情。你想并排成对的行,但一侧会比其他的多。
select * /* change to whatever you need */
from
(
select *, row_number() over (partition by "code#" order by "something") as rn
from tableA
) as a
full outer join /* sounds like maybe left outer join will work too */
(
select *, row_number() over (partition by "id#" order by "date" desc) as rn
from tableB
) as b
on b."id#" = a."code#" and b.rn = a.rn
实际上,我不知道您如何在 "apple" 和 "pizza" 之后得到 "ball" 而没有其他列进行排序。 SQL 表中的行没有任何排序,您不能依赖 select *...
中的默认列表或假设插入顺序很重要。