Pomocná tabulka se používá pro koncept levého / pravého spojení, ale nebylo to tak jednoduché.
Z mé odpovědi zde (Edit3) Zde :
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
Z upravené odpovědi od Uživatel fthiella ... ten příspěvek zde
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 |
+-------+
Výše uvedené je tedy obecná forma vložení csv do dotazu a vygenerování tabulky z něj.
Nyní vytvořte odvozenou tabulku (d
) z výše uvedeného zkombinujte pomocí RIGHT JOIN
s operačním kódem (toto schéma bylo zobrazeno v operačním kódu)
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;
Výsledky:
+-------------+-------+-------+-----------+------+------------+---------+--------+--------+
| 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 |
+-------------+-------+-------+-----------+------+------------+---------+--------+--------+