Mysql
 sql >> Datenbank >  >> RDS >> Mysql

Wie wähle ich das innere Join-Feld mit IF/case aus?

Versuchen Sie es mit dieser Abfrage (bearbeitet ) -

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

Noch eine Variante -

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