MYSQL JOIN on the same table

社会主义新天地 提交于 2019-12-13 07:39:24

问题


I currently have this query set-up:

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

This is because I want to merge two rows from the same table in one row. This is a simplified setup of the table

-----------------------------------------------------------
| page_id | content_id | title | location | display_order |
-----------------------------------------------------------
|    1    |     200    |  Foo  |   NULL   |     200       |
|    1    |     201    |  Baz  |   NULL   |     201       |
|   200   |     201    |  Bar  | jpg.jpg  |      1        |
-----------------------------------------------------------

And basically I want this result

---------------------------------
| content_id | title | location |
---------------------------------
|     200    |  Foo  | jpg.jpg  |
|     201    |  Baz  |   NULL   |
---------------------------------

Basically I want to select all topics, then also return the corresponding image if any. My current query only returns all topics with associated images. I tried LEFT and RIGHT OUTER JOINS but it doesn't seem to help.


回答1:


When you filter on an OUTER JOIN, you have to filter in the ON clause or as a derived table. When image.display_order = '1' is in the WHERE, it will always be an INNER JOIN

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' ) 

or

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' ) 


来源:https://stackoverflow.com/questions/6841851/mysql-join-on-the-same-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!