1

我有这样的疑问:

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');
4

1 回答 1

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 小提琴演示

这会给你:

|  NAME1 |  NAME2 |
-------------------
|    pen |    pen |
| pencil | (null) |
于 2013-03-20T08:44:58.740 回答