Mysql从表中加入限制

时间:2015-04-01 09:15:49

标签: mysql join limit

我正在进行下一个mysql查询

SELECT 
   `i`.`id_item`, 
   `c`.`id_category`
FROM `items` AS `i` 
LEFT JOIN `categories` AS `c` ON c.id_category = i.id_category 
WHERE (i.id_page = '7') 
ORDER BY `c`.`id_category` ASC, `i`.`id_item` ASC

项目可以属于某个类别,也可以不为其定义任何类别。 我需要将items表的结果限制为每个类别的X随机值,如果没有定义类别,则需要X随机值。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

尝试使用“分组依据”,然后将其限制为x值(LIMIT X)。我使用X = 5;

SELECT 
   `i`.`id_item`, 
   `c`.`id_category`
FROM `items` AS `i` 
LEFT JOIN `categories` AS `c` ON c.id_category = i.id_category 
WHERE (i.id_page = '7') GROUP BY i.id_category,i.id_item 
ORDER BY `c`.`id_category` ASC, `i`.`id_item` ASC LIMIT 5