Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/85.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 选择与特定记录相关但不与其他记录相关的记录_Sql_Sqlite - Fatal编程技术网

Sql 选择与特定记录相关但不与其他记录相关的记录

Sql 选择与特定记录相关但不与其他记录相关的记录,sql,sqlite,Sql,Sqlite,对于多对多关系,例如班级和学生,我想选择所有具有给定成员资格的班级 Students Classes StudentClass ========= ============ ================= id id student class -- --- -------- ------- 1 1

对于多对多关系,例如班级和学生,我想选择所有具有给定成员资格的
班级

Students         Classes        StudentClass
=========       ============    =================
id              id              student     class
--              ---             --------   -------
1               1               1           1
2               2               2           1
3                               3           1
4                               1           2
5                               2           2             
                                3           2
                                4           2
对于示例数据,如果我给出查询S1、S2、S3,它应该只返回类1,而排除类4,因为它包含一个额外的学生。

您可以按如下方式进行操作:

select class from StudentClass
where class in(
    select class from StudentClass where student in(1,2,3) 
    group by class having count(distinct student)=3
) group by class
having count(distinct student)=3

这里有一个使用条件聚合的选项:

select class
from studentclass
group by class
having count(case when student in (1,2,3) then 1 end) = 3
   and count(*) = 3

我会使用
横向
选择,但我不知道SQLite是否有。这只适用于样本数据@SumanKabir博士说,如果允许学生注册同一个班级,那将是一个非常糟糕的数据库设计。使用
distinct
很容易修复,不过:@Md.SumanKabir您也应该使用相同的重复数据尝试查询-您还缺少1个
distinct
。。。