0

我试图在两个表上做一个 LEFT JOIN/INNER JOIN/JOIN(忘记了差异,我的 MySQL 知识变得尘土飞扬......)。一个是categories,另一个是images

我想返回categories具有特定parent值的所有列表,并为每个类别返回该类别的最新图像images

我结束了这个查询:

SELECT * FROM `categories` AS `a`
         JOIN (SELECT `im`.`preview` AS `preview`,
                      `im`.`cid` AS `cid` 
               FROM `images` AS `im`
               ORDER BY `im`.`cid` DESC) AS `b`
               ON (`a`.`cid` = `b`.`cid`)
         GROUP BY `preview`

这将为类别表中的每一行从图像表中返回一个图像,但是如果我尝试对结果表进行条件/排序,我将开始得到奇怪的结果,例如将结尾更改为此或任何类似的变体:

WHERE `a`.`parent` = 10
GROUP BY `preview`
ORDER BY `a`.`cid

将不胜感激您对此有任何想法。提前致谢。

4

1 回答 1

1

您也可以不加入,只需使用子选择:

SELECT
c.*,
(SELECT preview 
 FROM images img 
 WHERE img.cid = c.cid 
 ORDER BY img.id DESC
 LIMIT 1) AS preview
FROM categories c
于 2012-12-11T12:13:13.193 回答