2012-10-22 112 views
2

一列組合2代表我有2個查詢:如何而分別選擇其他列

select id, count(something) selected from table1...; 
select id, count(something) rejected from table2...; 

第一個查詢給我

id selected 
------------ 
2 4 
3 5 

第二個查詢給我

id rejected 
------------ 
1 12 
3 13 

我希望通過單個查詢將它們組合成以下形式

id selected rejected 
-------------------- 
1 null  12 
2 4   null 
3 5   13 

我該如何做到這一點?

回答

3

你需要通過結合LEFT and RIGHT加入UNION ED結果模擬SQL ServerFULL OUTER JOIN但對我來說都是LEFT JOIN爲我所用這個

SELECT a.ID, a.selected, b.rejected 
FROM (selectedQuery) a 
     LEFT JOIN (rejectedQuery) b 
      ON a.ID = b.ID 
UNION 
SELECT a.ID, b.selected, a.rejected 
FROM (rejectedQuery) a 
     LEFT JOIN (selectedQuery) b 
      ON a.ID = b.ID 

SQLFiddle Demo

UPDATE 1

PostgreSQL支持FULL OUTER JOIN我的壞

SELECT COALESCE(a.ID,b.id) ID, a.selected, b.rejected 
FROM selectedQuery a 
     FULL OUTER JOIN rejectedQuery b 
      ON a.ID = b.ID 

SQLFiddle Demo

+4

是SQL Server的'FULL OUTER JOIN' PostgreSQL的'FULL OUTER JOIN'不同? –

+0

@CraigRinger我不好,我以爲'postgresql'不支持'全外連接'。謝謝。我真的很感激它! –

-1

你可以在id列中使用JOIN嗎?例如

SELECT s.id, COUNT(s.something) selected, COUNT(r.something) rejected 
FROM table1 s 
INNER JOIN table2 r ON r.id = s.id 
2

鑑於一些表達式返回數據:

select 
column1 id, 
column2 selected 
from (values (2 , 4),(3, 5)) table1; 

id | selected 
----+---------- 
    2 |  4 
    3 |  5 
(2 rows) 
select 
column1 id, 
column2 rejected 
from (values (1 , 12),(3, 13)) table2 
dbornside-# ; 
id | rejected 
----+---------- 
    1 |  12 
    3 |  13 
(2 rows) 

通常在ner連接不會產生正確的結果;只有在這兩個關係顯示

select * from 
    (select column1 id, column2 selected from (values (2 , 4),(3, 5)) table1) table1 
join (select column1 id, column2 rejected from (values (1 , 12),(3, 13)) table2) table2 
on table1.id = table2.id; 

id | selected | id | rejected 
----+----------+----+---------- 
    3 |  5 | 3 |  13 
(1 row) 

要想從右表中的行所有行,你需要一個right outer join,從左邊行是left outer join;爲了讓你使用一個full outer join

select * 
from (select column1 id, column2 selected from (values (2 , 4),(3, 5)) table1) table1 
FULL OUTER JOIN (select column1 id, column2 rejected from (values (1 , 12),(3, 13)) table2) table2 
on table1.id = table2.id; 

id | selected | id | rejected 
----+----------+----+---------- 
    2 |  4 | |   
    3 |  5 | 3 |  13 
    |   | 1 |  12 
(3 rows) 

雖然這看起來有點奇怪。那是因爲table1.idtable2.id不一樣;並且某些值在兩個表中都不存在。我們可以與coalesce()同一步驟他們聚集:

select COALESCE(table1.id, table2.id) id, 
     selected, 
     rejected 
from (select column1 id, column2 selected from (values (2 , 4),(3, 5)) table1) table1 
full outer join (select column1 id, column2 rejected from (values (1 , 12),(3, 13)) table2) table2 
on table1.id = table2.id; 

id | selected | rejected 
----+----------+---------- 
    2 |  4 |   
    3 |  5 |  13 
    1 |   |  12 
(3 rows)