rand() - 获取每个id的10个rand值的结果

时间:2018-02-08 13:56:06

标签: mysql

我的查询如下:

select s.name, m.c_id, m.r_stat, m.l_upd, m.desc, c.email 
from manual m 
join selling s 
join contact c 
on m.id=s.id 
and m.id=c.id 
where c.id in (21,22) order by rand() limit 10;

我希望每个身份证21的记录为10& 22.

1 个答案:

答案 0 :(得分:0)

使用变量:

SELECT *
FROM (
    select s.name, m.c_id, m.r_stat, m.l_upd, m.desc, c.email,
           @rn := IF(@id = c.id,
                     @rn + 1,
                     IF(@id := c.id, 1, 1)
                    ) as rn
    from manual m
    join selling s
      on m.id=s.id 
    join contact c
      on m.id=c.id
    cross join ( SELECT @rn := 0, @id := 0) as vars
    where c.id in (21,22) 
    order by c.id, rand()
   ) as t
where rn <= 10

;