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

我怎样才能做到这一点?

4

3 回答 3

3

您需要通过组合连接的SQL Servered结果来模拟(但在我的情况下,两者都像我以前那样FULL OUTER JOINUNIONLEFT and RIGHTLEFT 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 演示

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

于 2012-10-22T14:02:35.773 回答
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)

要从右侧表中获取所有行,您需要 a right outer join,左侧的行是 a 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.id不是同一列 table2.id并且某些值在两个表中都不存在。我们可以在同一步骤中使用 a 将它们收集在一起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)
于 2012-10-22T14:27:04.110 回答
-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
于 2012-10-22T14:02:07.973 回答