Sql 查询以查找标记到多行的 ID

Sql query to find Id tagged to multiple rows

我有一个学生 table 具有以下结构。

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

需要写一个query来获取subjectid等于1,3且studentid不等于4的studentId

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

输出studentId应该是123

但是没有成功。感谢任何帮助

最简单的方法是

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

尝试分组:

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

注意: 如果 subject_Id 字段的类型为 int,您可以考虑将 ('1', '3', '4') 更改为 (1, 3, 4)

注意 2: distinct 内的关键字 count 应该被使用,以防每个 studentId 有重复的 subject_Id 值。

您一次只能使用 1 个主题 ID,因此您的查询必须使用 or 而不是 and 也不要使用单一课程

Select 来自学生的 studentId,其中 subject Id=1 或 SubjectId =3 或
subjectId =4 .

试试这个