简体   繁体   English

从SQL联盟中删除重复项

[英]remove duplicates from sql union

I'm doing some basic sql on a few tables I have, using a union(rightly or wrongly) 我正在使用联合(对或错)在一些表上做一些基本的sql

but I need remove the duplicates. 但我需要删除重复项。 Any ideas? 有任何想法吗?

select * from calls
left join users a on calls.assigned_to= a.user_id
where a.dept = 4 
union
select * from calls
left join users r on calls.requestor_id= r.user_id
where r.dept = 4

Union will remove duplicates. Union将删除重复项。 Union All does not. Union All不。

除非您指定UNION ALL否则使用UNION自动删除重复的行: http : //msdn.microsoft.com/zh-cn/library/ms180026(SQL.90).aspx

Others have already answered your direct question, but perhaps you could simplify the query to eliminate the question (or have I missed something, and a query like the following will really produce substantially different results?): 其他人已经回答了您的直接问题,但是也许您可以简化查询以消除该问题(或者我错过了什么,而类似以下的查询会产生实质上不同的结果?):

select * 
    from calls c join users u
        on c.assigned_to = u.user_id 
        or c.requestor_id = u.user_id
    where u.dept = 4

If you are using T-SQL then it appears from previous posts that UNION removes duplicates. 如果您使用的是T-SQL,则UNION会从以前的帖子中删除重复项。 But if you are not, you could use distinct. 但是,如果不是这样,则可以使用“与众不同”。 This doesn't quite feel right to me either but it could get you the result you are looking for 这对我来说也不太合适,但可以为您提供所需的结果

SELECT DISTINCT *
FROM
(
select * from calls
left join users a on calls.assigned_to= a.user_id
where a.dept = 4 
union
select * from calls
left join users r on calls.requestor_id= r.user_id
where r.dept = 4
)a

Since you are still getting duplicate using only UNION I would check that: 由于您仍然只能使用UNION复制,因此我将检查以下内容:

  • That they are exact duplicates. 他们是确切的重复。 I mean, if you make a 我的意思是,如果您

    SELECT DISTINCT * FROM (<your query>) AS subquery

    you do get fewer files? 您得到的文件较少吗?

  • That you don't have already the duplicates in the first part of the query (maybe generated by the left join). 您在查询的第一部分中还没有重复项(可能是由左联接生成的)。 As I understand it UNION it will not add to the result set rows that are already on it, but it won't remove duplicates already present in the first data set. 据我了解, UNION不会将其添加到结果集中的行中,但不会删除第一个数据集中已经存在的重复项。

如果使用的是T-SQL,则可以在存储过程中使用临时表,并相应地更新或插入查询记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM