2013-05-31 71 views
1

如果有两个表如下文中提到:SELECT查询合并/连接两个表中的PostgreSQL

表1

day   acount 
    1998-03-01  8 
    1998-03-04  9 
    1998-03-05  10 
    1998-03-09  8 

表2

day   bcount 
    1998-03-02  9 
    1998-03-03  7 
    1998-03-05  4 
    1998-03-06  3 

可在选择查询以下面的格式以升序返回数据?

结果

day   acount  bcount 
    1998-03-01  8    0 
    1998-03-02  0    9 
    1998-03-03  0    7 
    1998-03-04  9    0 
    1998-03-05  10   4 
    1998-03-06  3    0 
    1998-03-09  8    0 

回答

7

我会建议使用全外连接到一起的day列的表格,得到的结果:

select coalesce(t1.day, t2.day) "day", 
    coalesce(t1.acount, 0) acount, 
    coalesce(t2.bcount, 0) bcount 
from table1 t1 
full outer join table2 t2 
    on t1.day = t2.day; 

SQL Fiddle with DemoCOALESCE函数将返回第一个非空结果,因此可用于获取同一列中的day值,然后替换acountbcount列中的nulls列。

2

@bluefeet's query是要走的路。我只是添加了一些语法糖和纠正。

SELECT day 
    , coalesce(t1.acount, 0) AS acount 
    , coalesce(t2.bcount, 0) AS bcount 
FROM  table1 t1 
FULL JOIN table2 t2 USING (day) 

SQL Fiddle.

  • 如果您使用较短的USING clause的JOIN条件(可能在这种情况下),你也不需要coalesce(t1.day, t2.day),因为这是正是无表什么dayUSING条款中列出的条件后解决。

  • 虽然它是确定跳过键字AS对表的别名,你不应该跳过它列别名 - 作为一个单独的段落Omitting the AS Key Word记录在手册中:

FROM项,标准和PostgreSQL都允许AS在作为非保留关键字的别名之前省略 。但是由于语法歧义,这对于输出列名是不切实际的 。