使用内连接选择随机4行

时间:2017-07-29 19:47:31

标签: mysql sql

我的表是这样的:

Inv-1000    2017-07-10 10:00:00 101 1000 10
Inv-1000    2017-07-10 10:30:00 101  600  6
Inv-1000    2017-07-10 10:30:00 102  400 20
Inv-1001    2017-07-11 10:30:00 101  300  5
Inv-1001    2017-07-11 10:30:00 102  200  5

我想从表test_ques

中选择每个skill_id的4个随机行

我想知道如何使用内部联接来完成上述操作并从技能表中获得分数。

2 个答案:

答案 0 :(得分:0)

在MySQL中,最简单的方法是枚举每个skill_id的行,然后选择四行:

select t.*
from (select t.*,
             (@rn := if(@s = skill_id, @rn + 1,
                        if(@s := skill_id, 1, 1)
                       )
             ) as rn
      from test_ques t cross join
           (select @s := -1, @rn := 0) params
      order by skill_id, rand()
     ) t
where rn <= 4;

答案 1 :(得分:0)

您可以使用GROUP_CONCAT()排序的RAND()将每个skill_id的ID存储在字符串中。然后使用FIND_IN_SET()

将子查询与表首先选择4连接
select q.*
from (
  select skill_id, group_concat(id order by rand()) as ids
  from test_ques
  group by skill_id
) sub
join test_ques q
  on  q.skill_id = sub.skill_id
  and find_in_set(q.id, sub.ids) <= 4

http://sqlfiddle.com/#!9/55730/6