MySQL为每个类别选择前10项

时间:2017-02-22 23:36:18

标签: php mysql

您好我有一个mysql数据库,其中有多个类别。我希望能够仅为每个类别提取前10个项目,例如:

我有下表,我想为name = a拉前2行,同样为name = b和name = c

-----------------------------------
name | value | description | logo
-----------------------------------
a    | 2.00  | its a letter| image
-----------------------------------
a    | 5.00  | its a letter| image
-----------------------------------
b    | 6.00  | its a letter| image
-----------------------------------
c    | 3.00  | its a letter| image
-----------------------------------
c    | 1.00  | its a letter| image
------------------------------------

这就是我所拥有的,因此农场后置过滤器是在调用时进入的一串对象。不幸的是,如果你能指出我正确的方向,那么它只会给我一共10个,非常感谢你!

代码:

SELECT * 
FROM object_list 
Where object IN (".$_POST['filter'].") 
ORDER BY date DESC, object ASC,id DESC

2 个答案:

答案 0 :(得分:3)

您可以通过以下查询获取群组count

SELECT name, value, 
@count := IF(@value = name, @count + 1, 1) AS count,
@value := name AS some_value
FROM test, (SELECT @count := 1, @value := NULL) a
WHERE test.name in ('a', 'b')

现在,如果您需要将每个行的行数限制为2,那么您只需将此查询包装到另一个选择中并添加一个条件,例如:

SELECT * 
FROM (
  SELECT name, value, 
  @count := IF(@value = name, @count + 1, 1) AS count,
  @value := name AS some_value
  FROM test, (SELECT @count := 1, @value := NULL) a
  WHERE test.name in ('a', 'b')) a
WHERE a.count <= 2;

这里是 SQL Fiddle

答案 1 :(得分:1)

这有用吗?

SELECT 
    yourtable.* 
FROM 
    yourtable 
    JOIN (
        SELECT 
            t1.name, 
            t1.value, 
            COUNT(t2.name) AS theCount 
        FROM yourtable t1 
        LEFT JOIN yourtable t2 ON t1.name = t2.name AND t1.value > t2.value 
        WHERE t1.name in ('a', 'b')
        GROUP BY t1.name, t1.value 
        HAVING theCount < 2
    ) AS dt USING (name, value);

来源:http://thenoyes.com/littlenoise/?p=36