indz
indz

Reputation: 13

MySQL - return only 1 record for each certain id

I'm a newbie with sql.

I have this table with these records:

table 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

I've tried this query SELECT subject_id FROM mark WHERE student_id =1

The results

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

How can i select the data with these result? I'm expecting something like this:

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

Thanks in advance.

Upvotes: 1

Views: 56

Answers (4)

Ramin Omrani
Ramin Omrani

Reputation: 3761

You can use GROUP BY:

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

Upvotes: 0

Naveen Kumar Alone
Naveen Kumar Alone

Reputation: 7668

Use DISTINCT clause to you can achieve it

SELECT DISTINCT subject_id FROM mark WHERE student_id =1;

Then you will get output as

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

Upvotes: 0

Mosty Mostacho
Mosty Mostacho

Reputation: 43434

Just use DISTINCT:

SELECT DISTINCT subject_id FROM mark WHERE student_id =1

Upvotes: 1

juergen d
juergen d

Reputation: 204756

Use distinct

SELECT distinct subject_id 
FROM mark 
WHERE student_id = 1

or group the data

SELECT subject_id 
FROM mark 
WHERE student_id = 1
group by subject_id

Upvotes: 0

Related Questions