如何组合单个列的2个表,同时分别选择其他列

时间:2012-10-22 13:56:58

标签: sql postgresql postgresql-9.1

我有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 个答案:

答案 0 :(得分:3)

您需要通过合并SQL Server联接的FULL OUTER JOIN结果来模拟UNION的{​​{1}} {但在我的情况下,LEFT and RIGHT 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

更新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

答案 1 :(得分: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)

通常的内连接不会产生正确的结果;只显示两个关系中的行

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)

答案 2 :(得分:-1)

你能在id列中使用JOIN吗? e.g。

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