MySQL - 每个特定id只返回1条记录

时间:2013-10-24 18:38:46

标签: mysql sql

我是sql的新手。

我有这些记录的表:

mark

----------------------------------------
student_id | subject_id | comp_id | mark
----------------------------------------
 1         |  1         |   28    |  5.5
 1         |  1         |   29    |  7.5
 1         |  1         |   30    |  9.0
 1         |  2         |   36    |  9.6
 1         |  2         |   37    |  6.0
 1         |  3         |   42    |  4.0

我已尝试过此查询SELECT subject_id FROM mark WHERE student_id =1

结果

subject_id
----------
1
1
1
2
2
3

如何选择具有这些结果的数据?我期待这样的事情:

subject_id
----------
1
2
3

提前致谢。

4 个答案:

答案 0 :(得分:1)

只需使用DISTINCT

SELECT DISTINCT subject_id FROM mark WHERE student_id =1

答案 1 :(得分:0)

使用distinct

SELECT distinct subject_id 
FROM mark 
WHERE student_id = 1

或对数据进行分组

SELECT subject_id 
FROM mark 
WHERE student_id = 1
group by subject_id

答案 2 :(得分:0)

使用 DISTINCT 子句来实现它

SELECT DISTINCT subject_id FROM mark WHERE student_id =1;

然后你会得到输出

subject_id
----------
1
2
3

答案 3 :(得分:0)

您可以使用GROUP BY

SELECT subject_id FROM mark WHERE student_id =1 GROUP BY student_id;