sql >> Base de Datos >  >> RDS >> Mysql

Combinación de resultados de consultas seleccionadas sin usar operadores establecidos (UNION)

Supongamos que tiene dos tablas que desea UNION

CREATE TABLE Table1
(`id` int, `name` varchar(32));
CREATE TABLE Table2
(`id` int, `name` varchar(32));

Y datos de muestra

tabla1:

| ID |  NAME |
|----|-------|
|  1 | name1 |
|  2 | name2 |
|  3 | name3 |

tabla2:

| ID |  NAME  |
|----|--------|
| 11 | name11 |
| 22 | name22 |
| 33 | name33 |
|  1 |  name1 |

Para emular 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 

Salida:

| ID |   NAME |
|----|--------|
|  1 |  name1 |
|  2 |  name2 |
|  3 |  name3 |
| 11 | name11 |
| 22 | name22 |
| 33 | name33 |
|  1 |  name1 |

Para emular UNION solo necesita agregar 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 

Salida:

| ID |   NAME |
|----|--------|
|  1 |  name1 |
|  2 |  name2 |
|  3 |  name3 |
| 11 | name11 |
| 22 | name22 |
| 33 | name33 |

Aquí está SQLFiddle demostración