sql >> Base de Datos >  >> RDS >> Mysql

¿Valores de columna dividida de MySQL para usar en la subconsulta?

No es una buena idea mantener los datos de esta manera.

La primera idea que se me ocurre es:http://sqlfiddle.com/#!2/ 1dd77/4

SELECT b.*, GROUP_CONCAT(a.name SEPARATOR ':')
FROM table2 as b
LEFT JOIN table1 as a
on b.var = a.id 
  OR  b.var regexp(CONCAT('^',a.id,':'))
  OR  b.var regexp(CONCAT(':',a.id,':'))
  OR  b.var regexp(CONCAT(':',a.id,'$'))
 GROUP BY b.id

EDITAR 1

Variante ordenada:http://sqlfiddle.com/#!2/1dd77/38

SELECT b.*, GROUP_CONCAT(a.name ORDER BY FIND_IN_SET(a.id, REPLACE(b.var,":",",")) SEPARATOR ':' )
FROM table2 as b
LEFT JOIN table1 as a
on b.var = a.id 
  OR  b.var regexp(CONCAT('^',a.id,':'))
  OR  b.var regexp(CONCAT(':',a.id,':'))
  OR  b.var regexp(CONCAT(':',a.id,'$'))
 GROUP BY b.id