我想合并 2 个 select 语句,结果将在记录方面不同,但是我想在第二个 select 语句中省略重复的结果(考虑某些列)
select id,name,[type],[parent] from table1 where [type] = 1
union
select * from table2 // but exclude results from this table where
// a record with the same type and parent exists
// in the first select
我已经想到了这一点(未测试):
select * from(
select *,rank() over(order by [type],[parent]) [rank] from(
select id,name,[type],[parent] from table1 where [type] = 1
union
select * from table2) t
) a where rank = 1
但这似乎不对,有没有更好的方法从第二次选择中排除重复项?
编辑:
每个项目都可以有附加组件。附加组件有两种创建方式:
1.在表1中专门创建了附加组件
2.公开定义类型x的项目必须有附加组件
第一个选择获取专门为 Items 创建的插件列表,table2 为所有 Items 创建一个插件列表,现在如果有专门为某个 Item 创建的插件,将会有一个重复的插件。
尝试
select * from table1
union
select * from table2
where not exists(select 1 from table1
where table2.parent = table1.parent
and table2.type = table1.type)
试试这个:
;WITH cte AS (
SELECT *, 1 AS SetID FROM table1 WHERE [Type] = 1
UNION ALL
SELECT *, 2 AS SetID FROM table2
)
,cte2 as (
SELECT *,
RANK() OVER (PARTITION BY [Type], [Parent] ORDER BY SetID) FROM cte) rk
FROM cte
)
SELECT * FROM cte2 WHERE rk = 1
我刚刚看到这个问题,我认为你可以使用左连接代替不存在,它具有更好的性能,所以查询应该如下所示:
select * from table1
union
select * from table2
left join table1 exists
on table2.parent = exists.parent
and table2.type = exists.type
where exists.id is null