MySQL:从连接返回第一行

时间:2015-06-14 12:27:41

标签: mysql sql

我有2张桌子"小测验" &安培; "用户",我需要返回第一个用户参加每个测验的列表,使用quiz_id:

表格结构

"quizzes" structure:
id     name
1     England
2     france
3     Japan
4     USA
5     UAE
6     Sweden
7     Italy
8     Brazil
9     South Korea
10    India


"users" structure:
id    user_id     quiz_id
1       1            1
2       1            2
3       2            1
4       3            4
5       1            4
6       5            9
7       2            9
8       3            8
9       3            9
10      3            7

我需要先运行查询才能返回" user_id"每个"测验",(由users.id ASC订购)

expected results:
quiz_id     user_id
   1           1
   2           1
   4           3
   7           3
   8           3
   9           5

感谢,

2 个答案:

答案 0 :(得分:1)

您首先按quiz分组并选择最小id,然后根据ids进行选择:

select quiz_id, user_id
from users 
where id in(select min(id) from users group by quiz_id)

答案 1 :(得分:0)

Select quiz_id, user_id
  from users
    Where  (quiz_id, id) in
       (
       Select quiz_id, min(id) id
         From users
           Group by quiz_id
       )