Laten we aannemen dat je twee tabellen hebt die je wilt UNION
CREATE TABLE Table1
(`id` int, `name` varchar(32));
CREATE TABLE Table2
(`id` int, `name` varchar(32));
En voorbeeldgegevens
tabel1:
| ID | NAME | |----|-------| | 1 | name1 | | 2 | name2 | | 3 | name3 |
tabel2:
| ID | NAME | |----|--------| | 11 | name11 | | 22 | name22 | | 33 | name33 | | 1 | name1 |
UNION ALL
emuleren
SELECT COALESCE(t1.id, t2.id) id,
COALESCE(t1.name, t2.name) name
FROM
(
SELECT TABLE_NAME <> 'table1' n
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = SCHEMA()
AND TABLE_NAME IN('table1', 'table2')
) t LEFT JOIN table1 t1
ON t.n = 0 LEFT JOIN table2 t2
ON t.n = 1
Uitgang:
| ID | NAME | |----|--------| | 1 | name1 | | 2 | name2 | | 3 | name3 | | 11 | name11 | | 22 | name22 | | 33 | name33 | | 1 | name1 |
UNION
emuleren je hoeft alleen maar DISTINCT
. toe te voegen
SELECT DISTINCT COALESCE(t1.id, t2.id) id,
COALESCE(t1.name, t2.name) name
FROM
(
SELECT TABLE_NAME <> 'table1' n
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = SCHEMA()
AND TABLE_NAME IN('table1', 'table2')
) t LEFT JOIN table1 t1
ON t.n = 0 LEFT JOIN table2 t2
ON t.n = 1
Uitgang:
| ID | NAME | |----|--------| | 1 | name1 | | 2 | name2 | | 3 | name3 | | 11 | name11 | | 22 | name22 | | 33 | name33 |
Hier is SQLFiddle demo