MYSQL 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 |
---------------------------------
基本上我想选择所有主题,然后还返回相应的图像(如果有)。我当前的查询仅返回具有关联图像的所有主题。我尝试了左外连接和右外连接,但似乎没有帮助。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您对 OUTER JOIN 进行过滤时,您必须在 ON 子句中或作为派生表进行过滤。当
image.display_order = '1'
位于 WHERE 中时,它将始终是 INNER JOIN或
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 JOINor