sql >> Database teknologi >  >> RDS >> Mysql

hvordan man vælger alle data, hvis input-array findes og ikke findes i mysql

En hjælpetabel bruges til venstre join / højre join-konceptet, men det var ikke helt så enkelt.

Fra mit svar her (Edit3) Her :

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
 

Fra et ændret svar fra Bruger fthiella ... det indlæg her

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å ovenstående er den generiske form for at ploppe en csv ind i en forespørgsel og generere en tabel ud af den.

Lav nu en afledt tabel (d ) ud af ovenstående, kombiner via RIGHT JOIN med op-kode (det skema blev vist i op-kode)

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; 
 

Resultater:

+-------------+-------+-------+-----------+------+------------+---------+--------+--------+ | 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 | +-------------+-------+-------+-----------+------+------------+---------+--------+--------+


  1. Udforskning af SQL Server 2016 Query Store GUI

  2. mybatis generator Kolonnenavnsmønster kan ikke være NULL eller tomt

  3. Oracle-klientinstallationsfejl - stien er for lang

  4. Online værktøjer til at prøve SQL design og forespørgsler