开发者

Mysql :Need to get unique field of two row on base of a column having two different value

开发者 https://www.devze.com 2023-02-10 19:17 出处:网络
I have a database structure like this. this is just dummy table. studentId | marks | grade |examId 125A23

I have a database structure like this.

this is just dummy table.

studentId | marks | grade |  examId
   1         25      A         23
   1         32      A         24
   2         13      B         24
   2         23      A         25
   2         34      A         26

I want to write a query to get the studentId of students who was present in both the exams. as a result, I should get studentId '1' but not '2' as student with studentId 2 was not present in exam-'23'.

I want studentIds which are present in examId 23 and 24, not any relation with count of records.

Right now I have write this query but it is not best pe开发者_C百科rformance wise.

SELECT studentId FROM students WHERE examId = 23 AND studentId in (select studentId FROM students where examId in (24) ) 

I am expecting query with better performance.

Ok , final answer as per conversation with Nicollof is

SELECT studentId FROM students WHERE examId IN(23, 24) GROUP BY studentId HAVING COUNT(studentId) = 2


select studentId from students 
where studentId in (23,24)
group by studentId 
having count(studentId) >1

The where clause filter the result and then the group by clause applied hence you will get what you wanted.


If you want to be able to tell which exams the students must have participated in (as opposed to the already suggested solutions, including all exams) you could just add a where clause

SELECT studentid 
FROM students WHERE examid IN(23, 24) 
GROUP BY studentid HAVING COUNT(*) > 1 

where 23 and 24 are the exam ids of the exams you are interested in


Assuming the rows are unique for the combination of studentID and examID, you can just try this -

select studentID from table
WHERE examID in (23, 24)
group by studentID
having count(*) > 1

Edited answer to accomodate the examID in (23,24) after seeing the edit in question and comments.

0

精彩评论

暂无评论...
验证码 换一张
取 消