我有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
我怎样才能做到这一点?
答案 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
更新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
答案 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.id
与table2.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