简体   繁体   English

在一对多关系查询中查找缺失的记录

[英]Find missing records in ONE-TO-MANY relationship query

I have 3 tables:我有 3 张桌子:

Class Class

Id ID ClassName班级名称
guid向导 1A 1A
guid向导 2A 2A

Subject主题

Id ID SubjectName主题名称
guid向导 Math数学
guid向导 Biography

SubjectOfEachClass每个类的主题

Id ID ClassId班级号 SubjectId主题 ID TeacherName老师的名字
guid向导 guid向导 guid向导 James Bond占士邦

The way I wanted these tables to work is:我希望这些表的工作方式是:

  • There will be 10 classes in table Class.表 Class 中将有 10 个类。
  • There will be 10 subjects in table Subject.表主题中将有 10 个主题。
  • Each class will has 10 subjects and for 10 classes there will be 100 records.每个 class 将有 10 个科目,对于 10 个班级,将有 100 条记录。

I ran into some problems, I queried the SubjectOfEachClass table and there are only 95 records.我遇到了一些问题,我查询了 SubjectOfEachClass 表,只有 95 条记录。 The query command I use to find the missing subjects is:我用来查找缺失主题的查询命令是:

SELECT *
FROM Subject s
JOIN (
    SELECT *
    FROM SubjectOfEachClass
    WHERE ClassId = 'guid'
) AS sc ON s.Id = sc.SubjectId

I replaced the ClassId several times until I found the class that misses some of the subjects.我多次更换ClassId,直到我发现错过了一些主题的class。

I reckon this way of querying is not efficient at all.我认为这种查询方式根本没有效率。 If I have 100 subjects and 100 classes, there will no chance that I will find the missing subjects.如果我有 100 个科目和 100 个班级,我就没有机会找到缺失的科目。

Try this:尝试这个:

SELECT c.id AS classId,
       count(sc.id) AS countOfSubjects
FROM SubjectOfEachClass AS sc
INNER JOIN Classes AS c ON c.id = sc.classId
GROUP BY c.id
ORDER BY countOfSubjects

The abnormal values will be floated.异常值将浮动。

Your primary table should be SubjectOfEachClass , then those foreign tables Subject and Class will join your primary table.您的主表应该是SubjectOfEachClass ,然后那些外部表SubjectClassjoin您的主表。

select *
from SubjectOfEachClass sc
inner join Subject s on s.guid=sc.guid
inner join Class c on c.guid=sc.guid
where sc.ClassId = 'guid'

to find every missing subject in all classes:查找所有课程中所有缺失的科目:

select c.id, c.classname , s.id , s.SubjectName
from class c
cross apply Subject s
where not exists (
   select 1 from SubjectOfEachClass sc 
   where sc.classid = c.id and sc.subjectid = s.id
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM