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

¿Cómo elegir el campo de unión interna con IF/case?

Pruebe esta consulta (editada ) -

SELECT c.*,
  CASE c.comment_type WHEN 8 THEN p1.photo_p_id WHEN 17 THEN p2.photo_id ELSE NULL END photo_id,
  CASE c.comment_type WHEN 8 THEN p1.column1 WHEN 17 THEN p2.column1 ELSE NULL END column1
FROM comments c
  LEFT JOIN photos p1
    ON c.object_id = p1.photo_p_id
  LEFT JOIN photos p2
    ON c.object_id = p2.photo_id

Una variante más -

SELECT c.*, p.*
FROM comments c
  JOIN photos p
    ON c.comment_type = 8 AND c.object_id = p.photo_p_id OR c.comment_type = 17 AND c.object_id = p.photo_id