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

¿Cómo obtener valor de la tabla mysql ordenada por otra tabla?

Además de tener la columna ReferenceType en la tabla ref_types, también necesita una columna Reference_ID que haga referencia al ID real en la tabla correspondiente como clave externa .

//ref_types table
ID Article_ID ReferenceType Reference_ID
1  1          book          1
2  1          article       1
3  1          article       2
4  1          book          2

Luego, puede evitar un bucle WHILE y dejar que MySQL haga el trabajo por usted con JOIN:

SELECT CONCAT('record ', rt.ID, ': ',
  COALESCE(ar.Article_Title, tr.Thesis_Title, br.Book_Title))
FROM ref_types rt
LEFT JOIN article_refs ar
  ON rt.ReferenceType = 'article' AND ar.ID = rt.Reference_ID
LEFT JOIN book_refs br
  ON rt.ReferenceType = 'book' AND br.ID = rt.Reference_ID
LEFT JOIN thesis_refs tr 
  ON rt.ReferenceType = 'thesis' AND tr.ID = rt.Reference_ID

Da el resultado:

record 1: book1
record 2: article1
record 3: article2
record 4: book2