En hjälptabell används för konceptet left join / right join men det var inte fullt så enkelt.
Från mitt svar här (Edit3) Här :
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
Från ett modifierat svar från Användare fthiella ... det inlägget här
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 |
+-------+
Så ovanstående är den allmänna formen för att lägga in en csv i en fråga och skapa en tabell ur den.
Gör nu en härledd tabell (d
) av ovanstående, kombinera via RIGHT JOIN
med op-kod (det schemat visades i op-koden)
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;
Resultat:
+-------------+-------+-------+-----------+------+------------+---------+--------+--------+
| 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 |
+-------------+-------+-------+-----------+------+------------+---------+--------+--------+