每个父ID的Mysql限制

时间:2013-01-14 08:00:08

标签: mysql limit where

如何限制id子句中每个WHERE的结果? 我的疑问是:

SELECT name 
FROM location_areas 
WHERE parent IN ("1,2,3") 
ORDER BY popularity,name    

父母不是唯一的。

我需要在id子句中为每个父WHERE获得10个结果。

例如表结构是:

id   name   parent
1    name    0
2    name    1
3    name    1
4    name    80
5    name    80
6    name    80
7    name    80
8    name    1

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT
   T.name,
   T.popularity,
   T.parent,
   T.rank
FROM
(
SELECT
   L.name,
   L.popularity,
   L.parent,
   @rank := IF(@parent = parent, @rank + 1, 1) rank,
   @parent := parent
FROM location_areas L,
(SELECT @rank := 1, @parent := NULL) R
) T
WHERE T.rank <= 10

修改

SELECT T.name, T.popularity, T.parent, T.level, T.rank
FROM (
         SELECT L.name, L.popularity,
             L.parent, L.level,
             @rank := IF(@parent = parent, @rank + 1, 1) rank,
             @parent := parent
         FROM location_areas L,
             (SELECT @rank := 1, @parent := NULL) R
         WHERE L.parent IN (".$ids.")
     ) T WHERE T.rank <= 10;

答案 1 :(得分:0)

你可以简单地做到这一点

SET @level = 0;
SET @group = '';

SELECT 
    name
FROM (
    SELECT 
        name ,
        parent
        @level := IF(@group = parent, @level+1, 1) AS level, 
        @group := parent as EGroup 
    FROM test
    WHERE parent IN ("1,2,3") 
    ORDER BY parent 
) rs
WHERE level < 11