简体   繁体   中英

Postgres SQL left outer join on the same table

I have such query:

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)

For this query I have such result:

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

but for select without join:

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

the result is:

name
------
pen
pencil

and second query:

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

gives result:

name
------
pen

I would expect for my first join query result:

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

How to achieve such result? I thought that way should work LEFT OUTER JOIN. Thanks for any suggestions in advance.

Ps. I need to catch differences in invoice items of corrective and corrected (related ) invoice.

Some sample data:

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

Try this instead:

 
 
 
  
  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;
 
  


Try this:

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

This will give you:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM