简体   繁体   中英

Select random 4 rows using inner join

My table is like this:

test_ques
------------------------------
id | ques | skill_id
1  | xyz  | 1
2  | xyz  | 1
3  | xyz  | 1
4  | xyz  | 1
5  | xyz  | 1
6  | xyz  | 2
7  | xyz  | 2
8  | xyz  | 2
9  | xyz  | 2
10 | xyz  | 2
11 | xyz  | 2
12 | xyz  | 3
13 | xyz  | 3
14 | xyz  | 3
15 | xyz  | 3
16 | xyz  | 3
17 | xyz  | 3

skills
------------
id | score
1  | 15
2  | 20
3  | 25

I want to select 4 random rows of each skill_id from table test_ques

I was wondering how to do the above and get score from skills table too using inner join.

In MySQL, the simplest method is to enumerate the rows for each skill_id and then choose four:

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;

You can store the ids for every skill_id in a string using GROUP_CONCAT() ordered by RAND() . Then join the subquery with the table selecting first 4 using 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM