Předpokládejme, že máte dvě tabulky, které chcete UNION
CREATE TABLE Table1
(`id` int, `name` varchar(32));
CREATE TABLE Table2
(`id` int, `name` varchar(32));
A ukázková data
tabulka1:
| ID | NAME | |----|-------| | 1 | name1 | | 2 | name2 | | 3 | name3 |
tabulka2:
| ID | NAME | |----|--------| | 11 | name11 | | 22 | name22 | | 33 | name33 | | 1 | name1 |
Chcete-li emulovat UNION ALL
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
Výstup:
| ID | NAME | |----|--------| | 1 | name1 | | 2 | name2 | | 3 | name3 | | 11 | name11 | | 22 | name22 | | 33 | name33 | | 1 | name1 |
Chcete-li emulovat UNION
stačí přidat DISTINCT
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
Výstup:
| ID | NAME | |----|--------| | 1 | name1 | | 2 | name2 | | 3 | name3 | | 11 | name11 | | 22 | name22 | | 33 | name33 |
Zde je SQLFiddle demo