简体   繁体   中英

SQL - OUTER JOIN a UNION-ed tables

I am new to sql. I have three tables, I want to UNION the first two tables then OUTER JOIN the result with the third table and only selecting a desired date.

I have already done the UNION but I don't know how the OUTER JOIN will come in.

These are my tables:

TABLE_1

| ID   | Name     |
-------------------
| 1    | John     |
| 2    | Peter    |
TABLE_2

| ID   | Name     |
-------------------
| 3    | Anne     |
| 4    | May      |
TABLE_3

| ID   | Name     | Date       |
--------------------------------
| 2    | Peter    | 2019-02-13 |
| 3    | Anne     | 2019-02-12 |
| 4    | May      | 2019-02-13 |

This is my query right now that only combines TABLE_1 and TABLE_2 :

SELECT ID, Name FROM TABLE_1 UNION SELECT ID, Name FROM TABLE_2

I want the final result to return ID and Name from TABLE_1 and TABLE_2 where the date in TABLE_3 is 2019-02-13 .

I want it to look like this:

| ID   | Name     | Date       |
--------------------------------
| 2    | Peter    | 2019-02-13 |
| 4    | May      | 2019-02-13 |

One approach here is to not use a union query, but instead to use exists subqueries to check for the existence of each TABLE_3 record in either of the first two tables.

SELECT t3.ID, t3.Name, t3.Date
FROM TABLE_3 t3
WHERE
    t3.Date = '2019-02-13' AND (
    EXISTS (SELECT 1 FROM TABLE_1 t1 WHERE t1.ID = t3.ID) OR
    EXISTS (SELECT 1 FROM TABLE_2 t2 WHERE t2.ID = t3.ID));

Try this,

SELECT A.* FROM
(
  SELECT ID, Name FROM TABLE_1 
  UNION
  SELECT ID, Name FROM TABLE_2
 ) AS A
 JOIN TABLE_3
 ON TABLE_3.ID = A.ID AND TABLE_3.DATE = "2019-02-13"

DB Fiddle Here

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