我制作了sqlfiddle示例:http://sqlfiddle.com/#!9/3bbb6d/1/0
SELECT
`Image`.`id`,
`Topic`.`title`
FROM
`images` AS `Image`, `topics` AS `Topic`
WHERE
`Image`.`vender_id` = 'model' AND `Topic`.`id` = IFNULL((SELECT article_id FROM articles_images WHERE image_id = `Image`.`id` ORDER BY id DESC LIMIT 0, 1), 999)
ORDER BY
`Image`.`id` DESC
LIMIT 10
结果:(正确)
id title
8
7
5 CCC
4 DDD
3 BBB
2 BBB
1
没有IFNULL(..., 999)
http://sqlfiddle.com/#!9/3bbb6d/2
结果:
id title
5 CCC
4 DDD
3 BBB
2 BBB
但是我还需要记录,并且记录中的空“ 标题” => id:8、7和1
是否可以不使用 IFNULL 而拥有所有记录?
+++更新+++
@Used_By_Already
感谢您的帮助。 我得到了结果:(它有两个ID为5的记录)
id title
8 (null)
7 (null)
5 AAA << X
5 CCC << correct
4 DDD
3 BBB
2 BBB
1 (null)
有两个具有相同 ID 的记录:5,我怎么只能获得其中一个 articles_images.id 最高的记录?
我需要得到的结果是:
id title
8
7
5 CCC
4 DDD
3 BBB
2 BBB
1
答案 0 :(得分:2)
使用左联接:
SELECT
I.id
,T.title
FROM images AS i
LEFT JOIN articles_images AS ai ON I.id = ai.image_id
LEFT JOIN topics AS t on ai.article_id = t.id
WHERE i.vender_id = 'model'
ORDER BY
i.id DESC
LIMIT 10
此结果与您请求的结果略有不同:
+----+-------+
| id | title |
+----+-------+
| 8 | NULL |
| 7 | NULL |
| 5 | AAA |
| 5 | CCC |
| 4 | DDD |
| 3 | BBB |
| 2 | BBB |
| 1 | NULL |
+----+-------+
针对RE修改的问题(包括NULL):
SELECT
I.id
,max(T.title) as title
FROM images AS i
LEFT JOIN articles_images AS ai ON I.id = ai.image_id
LEFT JOIN topics AS t on ai.article_id = t.id
WHERE i.vender_id = 'model'
GROUP BY
I.id
;
+----+-------+
| id | title |
+----+-------+
| 1 | NULL |
| 2 | BBB |
| 3 | BBB |
| 4 | DDD |
| 5 | CCC |
| 7 | NULL |
| 8 | NULL |
+----+-------+
请参阅:https://rextester.com/LCOBW94449
为保证您使用的是最高的article_,如果我建议这样做:
SELECT
I.id
,T.title
FROM ximages AS i
LEFT JOIN (
SELECT image_id, max(article_id) article_id
FROM xarticles_images
GROUP BY image_id
) AS ai ON I.id = ai.image_id
LEFT JOIN xtopics AS t on ai.article_id = t.id
WHERE i.vender_id = 'model'
ORDER BY
i.id DESC
;
答案 1 :(得分:1)
使用左联接
SELECT
i.`id`,
t.`title`
FROM
`images` AS i left join `topics` AS t on i.`vender_id` = 'model'
and t.`id`=i.article_id