sql - T-SQL - 在单个表中查找 PK 的差异(自联接?)

标签 sql tsql

我的情况是这样的。我有一个带有“组件”的pk“父级”的产品表数据看起来像这样

Parent(PK)    Component
Car1          Wheel
Car1          Tyre
Car1          Roof
Car2          Alloy
Car2          Tyre 
Car2          Roof
Car3          Alloy
Car3          Tyre
Car3          Roof 
Car3          Leather Seats

现在我想做的是一些查询,我可以输入两个代码并查看差异... IE 如果我输入“Car1”,“Car2”,它会返回类似的内容;

Parent       Component
Car1         Wheel
Car2         Alloy

因为这是两者之间的区别。如果我说“Car1”,“Car3”,我会期待;

Parent       Component
Car1         Wheel
Car3         Alloy
Car3         Leather Seats

非常感谢您对此事的帮助。

最佳答案

没有 GROUP BY 或 UNION:

create table Products (
    Parent varchar(20) not null,
    Component varchar(20) not null
)
insert into Products (Parent,Component)
select 'Car1','Wheel' union all
select 'Car1','Tyre' union all
select 'Car1','Roof' union all
select 'Car2','Alloy' union all
select 'Car2','Tyre' union all
select 'Car2','Roof' union all
select 'Car3','Alloy' union all
select 'Car3','Tyre' union all
select 'Car3','Roof' union all
select 'Car3','Leather Seats'
go
select
    ISNULL (a.Parent,b.Parent) as Parent,
    ISNULL (a.Component,b.Component) as Component
from
    Products a
        full outer join
    Products b
        on
            a.Component = b.Component and
            a.Parent = 'Car1' and
            b.Parent = 'Car3'
where
    (a.Parent = 'Car1' and b.Parent is null) or
    (b.Parent = 'Car3' and a.Parent is null)

关于sql - T-SQL - 在单个表中查找 PK 的差异(自联接?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2956102/

相关文章:

sql - 删除给定日期内的重复行组合

sql - 对相同日期和 ID 的列中的值求和

mysql - 如何在不使用辅助表的情况下连接两个在查询中应该只有一个的表? (使用两列进行左连接即可)

sql - 是否有任何已尝试和拒绝 CouchDB 的记录项目?

mysql - 查询中的 SQL 语法错误

sql - 合并两个表还是将它们分开?

mysql - MySQL 查询中的 double

SQL 2005 标准数据类型

sql-server - 在 SQL Server 中使用正则表达式

sql - 具有包含列的索引,有什么区别?