考虑到插入了多个类别或类型,我需要从表中获取底部N值。
我的表:
CREATE TABLE `Table1` (
`name` VARCHAR(250) NOT NULL,
`total` INT(11) NOT NULL,
`type` INT(11) NOT NULL
)
ENGINE=InnoDB;
有些值:
|| *name* || *total* || *type* ||
|| Clock || 12 || 103 ||
|| Brief Case || 21 || 103 ||
|| Pencil || 34 || 103 ||
|| Lollypop || 45 || 103 ||
|| Notebook || 67 || 142 ||
|| Rubber Band || 3 || 143 ||
|| Smartphone || 1 || 143 ||
到目前为止我得到了什么:
SELECT name,total from Table1 ORDER BY TOTAL ASC LIMIT 3 where type=143;
但是我需要对每个类别使用一个查询获得相同的结果。
试过这个:
SELECT name,total from Table1 ORDER BY TOTAL ASC LIMIT 3 GROUP BY type;
但这是错误的。正如预期的那样,我只从所有记录中检索3条记录,而不是从每个类别中检索3条记录。
答案 0 :(得分:0)
试试这个:
SELECT name,total from Table1 as t1
WHERE t1.name in (SELECT t2.name FROM Table1 as t2 WHERE t1.type = t2.type ORDER BY t2.TOTAL ASC LIMIT 3)