MYSQL JOIN在同一个表上

时间:2011-07-27 09:05:25

标签: mysql inner-join outer-join

我目前有这个查询设置:

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'

这是因为我想在一行中合并同一个表中的两行。这是表格的简化设置

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

基本上我想选择所有主题,然后还返回相应的图像(如果有的话)。我当前的查询仅返回包含相关图像的所有主题。我尝试了LEFT和RIGHT OUTER JOINS,但它似乎没有帮助。

1 个答案:

答案 0 :(得分:1)

在OUTER JOIN上过滤时,必须在ON子句中过滤或作为派生表过滤。当image.display_order = '1'在WHERE中时,它将始终为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' ) 

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