在两个结果集联合时避免重复

时间:2016-10-21 14:07:02

标签: postgresql union

我有2个不同的查询,其结果如下:

First One:
 user | score | someId 
 ali  |  13   | 12314
      |       | 12323
 veli |  19   | 12345
      |  12   | 12346

Second One:
user  | score | someId 
      |       | 12314
  ali | 12    | 12323
 veli | 19    | 12345

我想要的输出如下:

user  | score | someId 
  ali | 13    | 12314
  ali | 12    | 12323
 veli | 19    | 12345
      |  12   | 12346

然而真正的结果是这样的:

user  | score | someId 
  ali | 13    | 12314
      |       | 12314
  ali | 12    | 12323
 veli | 19    | 12345
      |  12   | 12346

由于第一行和第二行不相同,因此不同的功能无法解决我的问题。如果我在(someId)上应用distinct,那么我将失去其中一个,这可能是结果中的第二行。我怎么能加入这些conjucate 2结果?

我的查询是这样的:

select a.user, b.score, a.id from a join b on a.first_game = b.id
union
select a.user, b.score, a.id from a join b on a.second_game = b.id 

修改

用户和得分字段都可以为空。

4 个答案:

答案 0 :(得分:0)

您可以在查询和状态

上添加where子句
WHERE a.user IS NOT NULL

另一种选择是将结果视为一个表,并在其上写一个包装器,如

SELECT t.user, t.score, t.id 
 FROM (select a.user, b.score, a.id from a join b on a.first_game = b.id
       union
       select a.user, b.score, a.id from a join b on a.second_game = b.id) t
 WHERE t.user IS NOT NULL

答案 1 :(得分:0)

使用DISTINCT ON()时,除非您指定ORDER BY子句,否则顺序是不确定的。您是否尝试过使用order by子句来确保您的行正确排序(基本上选择了打破平局顺序)?试试这个:

SELECT DISTINCT ON (id) * FROM (
    select a.user, b.score, a.id from a join b on a.first_game = b.id
    union
    select a.user, b.score, a.id from a join b on a.second_game = b.id
) U
ORDER BY id, user IS NOT NULL DESC, score IS NOT NULL DESC

答案 2 :(得分:0)

所以你不想要任何空行?

select * from(
select a.user, b.score, a.id from a join b on a.first_game = b.id
where b.score is not null
union all
select a.user, b.score, a.id from a join b on a.second_game = b.id 
where b.score is not null
) user_scores

答案 3 :(得分:0)

我可能没有正确理解这个问题,但试一试。

假设您的第一个结果是 t1 ,其次是 t2 。然后以下可能会做到这一点:

select coalesce(t1.user, t2.user) as user, 
coalesce(t1.score, t2.score) as score, t1.id 
from t1 full outer join t2 on t1.id = t2.id