简体   繁体   中英

Sql query to find Id tagged to multiple rows

I have a student table with the below structure.

StudentId    StudentName     SubjectId
     123         Lina              1
     456         Andrews           4
     123         Lina              3 
     123         Lina              4
     456         Andrews           5

Need to write a query to get the studentId where the subjectid is equal to 1,3 and studentid is not equal to 4

Select studentId from student  where subject Id='1' and SubjectId ='3' and     
subjectId ='4' .

Output studentId should be 123

But it does not work out. Any help is appreciated

The easiest way would be

select StudentId from student
where SubjectId in (1,3,4)
group by StudentId
having count(distinct SubjectId) = 3

Try with grouping:

Select studentId 
from student  
where subject_Id in ('1', '3', '4')
group by studentId 
having count(distinct subject_Id) = 3

Note: You might consider changing ('1', '3', '4') to (1, 3, 4) if subject_Id field is of type int .

Note2: distinct keyword inside count should be used in case you have duplicate subject_Id values per studentId .

At once you can use only 1 subject id, for that your query must use or instead of and And don't use single course as well

Select studentId from student where subject Id=1 or SubjectId =3 or
subjectId =4 .

Try this once

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