选择n行的n个随机组

时间:2012-06-24 18:58:25

标签: mysql sql

我有这张表services,数据如下:

service_id  bepro_id    service_name
        1   1   Virtuales
        2   2   Logos1
        3   3   Diseño C
        4   1   Formatos A3
        203 77  Dasdad
        6   2   Publi
        8   4   edificios Vi
        9   3   Maquillaje D
        10  7   Servicio 10 Serv
        11  4   servicio 11 tittle
        14  3   Lorem ipsum dol
        15  30  servicio 15 title
        16  4   Titulo TituloTitulo
        17  8   servicio 17 title ñ
        19  11  Retoques digital 
        20  4   servicio 20 title
        26  5   service 26 title
        27  7   servicio 27 tittle
        183 3   Excepteur sint occaecat 
        188 3    Duis aute irure dolor 
        185 3   Cillum dolore eu fugiat
        186 3   Eserunt mollit anim i
        190 3   Lorem ipsum dolor
        191 3   general para ed
        192 3   Ingenieria
        193 3   letras
        194 2   bocetos
        196 60  Retoque fotografico
        199 60  Maquetacion de 
        198 28  Revistas en General

我想从每个bepro_id 1到8个8个不同的随机值中选择每个值(最小1,最大8)bepro_id

我的意思是最多64行或最少8行。然后我必须加入表“users”,其中services.bepro_id = users.users_id。

这样每个值只选择一个随机行(我需要每个值最少1个值,每个值最多8个)@Andomar帮助我很多,但似乎不起作用,它看起来很复杂,是唯一的我能这样做的方式吗?:

SELECT * FROM  `services` GROUP BY bepro_id ORDER BY RAND( ) LIMIT 8

提前谢谢

1 个答案:

答案 0 :(得分:2)

您可以使用MySQL变量技巧用行号标记每一行。可以使用inner join将结果限制为N bepro。以下示例为3个随机bepro返回1-2个随机服务。更改这些值应该很容易。

这是我要感谢@Andomar:

select  *
from    (
        select  distinct bepro_id
        from    services
        order by
                rand()
        limit   8 -- Eight random bepro_id's
        ) bepro
join    (
        select  if(@last_bepro = bepro_id, @rn := @rn + 1, @rn := 1) as rn
        ,       (@last_bepro := bepro_id)
        ,       service_id
        ,       bepro_id
        ,       service_name
        from    services
        cross join
                (select @rn := 0, @last_bepro := -1) r
        order by
                bepro_id
        ) serv
on      serv.bepro_id = bepro.bepro_id
join    users 
on      users.id = bepro.bepro.id
where   serv.rn <= 8 -- 8 services max , 1 min per bepro_id
order by
        rand();

Live example at SQL Fiddle.