MySQL按重复模式排序

时间:2014-03-12 08:00:40

标签: php mysql

我在MySQL表中有一个产品列表,如下所示:

id_manufacturer | id_product
1                 1
2                 5
3                 6
4                 10
1                 14
2                 18
3                 25
4                 27
1                 28
2                 29
3                 30
4                 35
1                 40
2                 42
3                 45
4                 55

我希望的结果是找回制造商订购的产品清单,但是每个产品只有3个,然后再重复一次:

id_manufacturer | id_product
1                 1
1                 14
1                 28
2                 5
2                 29
2                 18
3                 6
3                 25
3                 30
4                 27
4                 35
4                 10
1                 154
1                 145
1                 285

有人可以帮忙吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以将嵌套查询与局部变量一起使用。 试试这个:

select 
    id_manufacturer, 
    id_product
from (
                select 
                    id_manufacturer, 
                    id_product,
                    case when (@prev_id <> id_manufacturer) then (@num := 1) else (@num := @num + 1) end as dummy1,
                    (@prev_id := id_manufacturer) as dummy2,
                    @num as rownum
                from tbl, (select @prev_id := -1, @num := 0) x
                order by 
                    id_manufacturer asc, 
                    id_product asc
) subq
where
    rownum <= 3