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

MYSQL JOIN für dieselbe Tabelle

Wenn Sie nach einem OUTER JOIN filtern, müssen Sie in der ON-Klausel oder als abgeleitete Tabelle filtern. Wenn image.display_order = '1' im WHERE steht, wird es immer ein INNER JOIN sein

SELECT 
  topic.content_id, 
  topic.title, 
  image.location 
FROM 
  mps_contents AS topic 
  LEFT JOIN
  mps_contents AS image ON topic.content_id = image.page_id
             AND image.display_order = '1'  
WHERE 
  topic.page_id = (SELECT page_id FROM mps_pages WHERE page_short_name = 'foo' ) 

oder

SELECT 
  topic.content_id, 
  topic.title, 
  image.location 
FROM 
  mps_contents AS topic 
  LEFT JOIN
  (
   SELECT *
   FROM mps_contents
   WHERE display_order = '1'
  ) AS image ON topic.content_id = image.page_id
WHERE 
  topic.page_id = (SELECT page_id FROM mps_pages WHERE page_short_name = 'foo' )