Misalkan Anda memiliki dua tabel yang ingin Anda UNION
CREATE TABLE Table1
(`id` int, `name` varchar(32));
CREATE TABLE Table2
(`id` int, `name` varchar(32));
Dan contoh data
tabel1:
| ID | NAME | |----|-------| | 1 | name1 | | 2 | name2 | | 3 | name3 |
tabel2:
| ID | NAME | |----|--------| | 11 | name11 | | 22 | name22 | | 33 | name33 | | 1 | name1 |
Untuk meniru 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
Keluaran:
| ID | NAME | |----|--------| | 1 | name1 | | 2 | name2 | | 3 | name3 | | 11 | name11 | | 22 | name22 | | 33 | name33 | | 1 | name1 |
Untuk meniru UNION
Anda hanya perlu menambahkan 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
Keluaran:
| ID | NAME | |----|--------| | 1 | name1 | | 2 | name2 | | 3 | name3 | | 11 | name11 | | 22 | name22 | | 33 | name33 |
Ini SQLFiddle demo