Postgres SQL将外连接保留在同一个表中

时间:2013-03-20 08:42:36

标签: sql postgresql

我有这样的疑问:

SELECT c.name, i.name FROM inv_invoice_items c 
LEFT OUTER JOIN inv_invoice_items i ON i.name = c.name
WHERE c.id_invoice = 2108 AND i.id_invoice = (SELECT id_invoice FROM inv_invoices WHERE id =   2108)

对于此查询,我有这样的结果:

name  | name
-------------
pen   | pen

但是对于没有加入的选择:

SELECT c.name FROM inv_invoice_items c
WHERE c.id_invoice = 2108

结果是:

name
------
pen
pencil

和第二个查询:

SELECT i.name FROM inv_invoice_items i
WHERE i.id_invoice = (SELECT id_invoice FROM inv_invoices WHERE id = 2108)

给出结果:

name
------
pen

我希望第一次加入查询结果:

name   | name
---------------
pen    | pen
pencil | NULL

如何实现这样的结果?我认为这种方式应该工作LEFT OUTER JOIN。感谢您提前提出任何建议。

聚苯乙烯。我需要记录纠正和更正(相关)发票的发票项目的差异。

一些示例数据:

create table inv_invoices (id bigint, id_invoice bigint, primary key(id));
create table inv_invoice_items (id bigint, id_invoice bigint NOT NULL, name character varying(100) NOT NULL, primary key (id));
insert into inv_invoices values (2105, NULL), (2106, NULL), (2107, NULL), (2108, 2106);
insert into inv_invoice_items values (1000, 2105, 'pen'), (1001, 2105, 'pencil'), (1002,2106, 'pen'), (1003, 2107, 'rubber'), 
(1004, 2107, 'pencil'), (1005, 2108, 'pen'), (1006, 2108, 'pencil');

1 个答案:

答案 0 :(得分:3)

改为尝试:

SELECT DISTINCT c.name, i.name 
FROM inv_invoice_items            AS c 
LEFT OUTER JOIN inv_invoice_items AS i   ON i.name       = c.name 
                                        AND c.id_invoice = 2108
LEFT OUTER JOIN inv_invoices      AS i2  ON i.id_invoice = i2.id_invoice 
                                        AND i2.id        = 2108;

<击>


试试这个:

SELECT
  t.name AS name1,
  v.name AS name2
FROM
(
  SELECT c.name 
  FROM inv_invoice_items c
  WHERE c.id_invoice = 2108
) AS t
LEFT JOIN
(
  SELECT i.name 
  FROM inv_invoice_items i
  WHERE i.id_invoice = (SELECT id_invoice 
                        FROM inv_invoices 
                        WHERE id = 2108)
) AS v ON t.name = v.name;

SQL Fiddle Demo

这会给你:

|  NAME1 |  NAME2 |
-------------------
|    pen |    pen |
| pencil | (null) |