Se utiliza una tabla de ayuda para el concepto de combinación izquierda/derecha, pero no era tan simple.
De mi respuesta aquí (Edit3) Aquí :
CREATE TABLE 4kTable
( -- a helper table of about 4k consecutive ints
id int auto_increment primary key,
thing int null
)engine=MyISAM;
insert 4kTable (thing) values (null),(null),(null),(null),(null),(null),(null),(null),(null);
insert 4kTable (thing) select thing from 4kTable;
insert 4kTable (thing) select thing from 4kTable;
insert 4kTable (thing) select thing from 4kTable;
insert 4kTable (thing) select thing from 4kTable;
insert 4kTable (thing) select thing from 4kTable;
insert 4kTable (thing) select thing from 4kTable;
insert 4kTable (thing) select thing from 4kTable;
insert 4kTable (thing) select thing from 4kTable;
insert 4kTable (thing) select thing from 4kTable;
-- verify:
-- select min(id),max(id),count(*) from 4kTable;
-- 1 4608 4608
ALTER TABLE 4kTable ENGINE = InnoDB; -- *********** it is now InnoDB
De una respuesta modificada de Usuario fthiella ... esa publicación aquí
select SUBSTRING_INDEX(SUBSTRING_INDEX(@str, ',', 4k.id), ',', -1) name
from
4kTable 4k
cross join (select @str:='SMITH,WARD,KING,TOM') vars
on CHAR_LENGTH(@str)
-CHAR_LENGTH(REPLACE(@str, ',', ''))>=4k.id-1;
+-------+
| name |
+-------+
| SMITH |
| WARD |
| KING |
| TOM |
+-------+
Entonces, lo anterior es la forma genérica de colocar un csv en una consulta y generar una tabla a partir de él.
Ahora haz una tabla derivada (d
) fuera de lo anterior, combine a través de RIGHT JOIN
con código de operación (ese esquema se mostró en el código de operación)
select d.name as rtable_name,e.empno,e.ename,e.job,e.mgr,e.hiredate,e.sal,e.comm,e.deptno
from emp e
right join
( select SUBSTRING_INDEX(SUBSTRING_INDEX(@str, ',', 4k.id), ',', -1) name
from 4kTable 4k
cross join (select @str:='SMITH,WARD,KING,TOM') vars
on CHAR_LENGTH(@str)
-CHAR_LENGTH(REPLACE(@str, ',', ''))>=4k.id-1
) d
on d.name=e.ename;
Resultados:
+-------------+-------+-------+-----------+------+------------+---------+--------+--------+
| rtable_name | empno | ename | job | mgr | hiredate | sal | comm | deptno |
+-------------+-------+-------+-----------+------+------------+---------+--------+--------+
| SMITH | 7369 | SMITH | CLERK | 7902 | 1980-12-17 | 800.00 | NULL | 20 |
| WARD | 7521 | WARD | SALESMAN | 7698 | 1981-02-22 | 1250.00 | 500.00 | 30 |
| KING | 7839 | KING | PRESIDENT | NULL | 1981-11-17 | 5000.00 | NULL | 10 |
| TOM | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
+-------------+-------+-------+-----------+------+------------+---------+--------+--------+