MySQL加入分组和排序

时间:2012-12-11 12:06:55

标签: mysql join

我试图在两张桌子上进行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

非常感谢您对此有任何想法。谢谢你提前。

1 个答案:

答案 0 :(得分:1)

你也可以不加入,只使用subselect:

SELECT
c.*,
(SELECT preview 
 FROM images img 
 WHERE img.cid = c.cid 
 ORDER BY img.id DESC
 LIMIT 1) AS preview
FROM categories c