我的表是这样的:
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个随机行我想知道如何使用内部联接来完成上述操作并从技能表中获得分数。
答案 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()
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