【问题标题】:Sql query to find Id tagged to multiple rowsSql 查询以查找标记为多行的 Id
【发布时间】:2023-03-16 01:04:01
【问题描述】:

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

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

需要编写查询来获取subjectid等于1,3且studentid不等于4的studentId

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

输出 studentId 应该是 123

但这并没有成功。任何帮助表示赞赏

【问题讨论】:

    标签: mysql sql oracle10g


    【解决方案1】:

    尝试分组:

    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: count 内的 distinct 关键字应该使用,以防每个 studentId 有重复的 subject_Id 值。

    【讨论】:

    • 感谢您的回复。如果我需要添加条件subjectid不等于4。如何修改查询
    【解决方案2】:

    最简单的方法是

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

    【讨论】:

    • 感谢您的回复。如果我需要添加条件subjectid不等于4。如何修改查询
    【解决方案3】:

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

    从科目 ID=1 或 SubjectId =3 的学生中选择 studentId 或
    subjectId =4 .

    试试这个

    【讨论】:

      猜你喜欢
      • 2012-08-16
      • 1970-01-01
      • 2012-05-31
      • 2016-05-21
      • 1970-01-01
      • 1970-01-01
      • 2015-05-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多