简体   繁体   中英

How to select just one id from a set of repetitive records in SQL and select only one of the corresponding values

So I have this table called students_classrooms which represents the relationship between students and classrooms. I have been wondering if there is a way I could get for each classroom one randomly assign student only with SQL query.

Looking for result like this: classroom - student (2,3)(3,77)

students are selected ranmdomly.

I have been trying different configurations solutions, but non of them seems to be working, would appreciate any suggestions, thanks!!

SELECT student_id, classroom_id
from students_classrooms
where classroom_id in (2,3)

学生教室

I think you need something like:

select ( 
         select t2.student_id 
         from students_classrooms t2 
         where t2.classroom_id = t1.classroom_id 
     order by rand() limit 1 
    ) as student_id,
          t1.classroom_id
from students_classrooms t1
group by classroom_id
order by rand() ;

The subquery randomly searches the same table, referencing the classroom_id, generating a random list

Demo

Here's an idea:

SELECT classroom_id,
       SUBSTRING_INDEX(GROUP_CONCAT(student_id ORDER BY RAND()),',',1) AS student
FROM students_classrooms 
WHERE classroom_id IN (2,3)
GROUP BY classroom_id;

Use GROUP_CONCAT(student_id ORDER BY RAND()) then extract the first student_id appeared in the GROUP_CONCAT() list using SUBSTRING_INDEX() .

Fiddle

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