Per il concetto di join sinistro/destro viene utilizzata una tabella di supporto, ma non era così semplice.
Dalla mia risposta qui (Modifica3) Qui :
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
Da una risposta modificata da Utente fthiella ... quel post qui
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 |
+-------+
Quindi quanto sopra è la forma generica di inserire un CSV in una query e generare una tabella da esso.
Ora crea una tabella derivata (d
) tra quanto sopra, combinare tramite RIGHT JOIN
con codice operativo (quello schema è stato mostrato in codice operativo)
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;
Risultati:
+-------------+-------+-------+-----------+------+------------+---------+--------+--------+
| 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 |
+-------------+-------+-------+-----------+------+------------+---------+--------+--------+