2016-10-21 32 views
0

我有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)上應用截然不同的,那麼我將失去其中的一個,這可能是結果中的第二行。我怎麼能加入這些結果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 

編輯

兩個用戶和得分字段爲空。

+0

我不清楚。你能告訴你想要什麼:提到的**作爲**期望的輸出**或提到的**作爲**實際結果** – Nikhil

回答

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 
0

您可以在查詢和狀態添加where子句

WHERE a.user IS NOT NULL 

另一種選擇是把結果作爲一個表,當您使用DISTINCT ON()寫這樣

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 
+0

我編輯了我的問題,以便用戶和分數字段都可以爲空 –

+0

看起來你想要第一個和第二個用戶不是null的所有東西?在這種情況下,你可以使用union和第二個查詢中的where子句。 – Sebz

0

的包裝在它,除非您指定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 
+0

我編輯了我的問題,以便用戶和分數字段都可以爲空 –

+0

這應該仍然有效,因爲它會給你所有不同的id使用tiebreaker條件,指定你希望有非空用戶和分數第一。 – pault

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