[英]Find missing records in ONE-TO-MANY relationship query
I have 3 tables:我有 3 张桌子:
Class Class
Id ![]() |
ClassName![]() |
---|---|
guid![]() |
1A ![]() |
guid![]() |
2A ![]() |
Subject主题
Id ![]() |
SubjectName![]() |
---|---|
guid![]() |
Math![]() |
guid![]() |
Biography![]() |
SubjectOfEachClass每个类的主题
Id ![]() |
ClassId![]() |
SubjectId![]() |
TeacherName![]() |
---|---|---|---|
guid![]() |
guid![]() |
guid![]() |
James Bond![]() |
The way I wanted these tables to work is:我希望这些表的工作方式是:
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
,然后那些外部表Subject
和Class
将join
您的主表。
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.