SQL查询在大型数据集上工作但速度很慢?

时间:2014-03-06 18:54:01

标签: sql sqlite

尝试创建一个查询,选择您已经采取先决条件的下一季度的课程。让我感到困难的是,如果课程有多种先决条件而你已经完成了一门课程。

这两个表是记录(学生,课程)和先决条件(课程,Prereq)

我的查询尝试有效但速度很慢:

select r.Student, p.Course 
from Record r, Prerequisite p where r.Course = p.Prereq and p.Course not in
( select Course from (select r.Student, p.Course from Record r, Prerequisite p 
  where r.Course <> p.Prereq) a where a.Student = r.Student);

任何帮助都会很棒!

示例数据

CREATE TABLE Prerequisite (Course CHAR(32), Prereq CHAR(32));
CREATE TABLE Record (
    Student CHAR(32), 
    Course CHAR(32),
    PRIMARY KEY (Student, Course)
);
INSERT INTO Prerequisite VALUES ('Class 3', 'Class 1');
INSERT INTO Prerequisite VALUES ('Class 6', 'Class 4');
INSERT INTO Prerequisite VALUES ('Class 4', 'Class 1');
INSERT INTO Prerequisite VALUES ('Class 4', 'Class 3');
INSERT INTO Prerequisite VALUES ('Class 8', 'Class 2');
INSERT INTO Prerequisite VALUES ('Class 8', 'Class 6');
INSERT INTO Prerequisite VALUES ('Class 5', 'Class 2');
INSERT INTO Prerequisite VALUES ('Class 9', 'Class 8');
INSERT INTO Prerequisite VALUES ('Class 7', 'Class 5');
--added Class 10 requires Class 1 and Class 2
INSERT INTO Prerequisite VALUES ('Class 10', 'Class 1');
INSERT INTO Prerequisite VALUES ('Class 10', 'Class 2');

INSERT INTO Record VALUES ('Bob', 'Class 1');
INSERT INTO Record VALUES ('Jan', 'Class 2');
--Bob Takes both Class 1 and Class 2 thus he can take Class 10
INSERT INTO Record VALUES ('Bob', 'Class 2');

所以结果应该是

Bob | Class 3
Jan | Class 5
Bob | Class 5
Bob | Class 10

编辑:添加了小样本数据

edit2:有关其他详细信息,请参阅以下评论

编辑3:刚刚意识到我的解决方案在查看Mhai的新解决方案并制作一个表明它不起作用的测试用例时没有工作,我的工作也没有。< / p>

使用新的测试用例更新了示例数据,也就是说,如果您的学生已经学习了课程的两个先决条件,那么他们应该参加该课程。

2 个答案:

答案 0 :(得分:2)

尝试

SELECT r.Student, p.Course FROM Record r
JOIN Prerequisite p
ON r.Course = p.Prereq
LEFT JOIN (
     select  r.Student, p.Course FROM Record r
     JOIN Prerequisite p 
     ON p.Prereq<>r.Course)x
ON x.Student = r.Student
WHERE p.Course IS NULL

SELECT  r.Student,p.Course,pp.Prereq FROM Record r
JOIN Prerequisite p
ON r.Course = p.Prereq
JOIN Prerequisite pp
ON
p.Course=pp.Course
GROUP BY p.Course HAVING COUNT(*)=1

这将找到只有1个要求的所有记录

Fiddle

答案 1 :(得分:0)

select r.Student, p.Course 
from Record r inner join Prerequisite p on p.Prereq = r.course where not exists(
( select pr.Course from Prerequisite pr inner join records rr on rr.student=r.student 
where pr.Prereq =r.course ))

试试这个,如果你有可能有脏记录,请使用NOLOCK。