SQLite中的所有操作员替代方案



我正在尝试找出在sqlite中使用 all的等效物(不支持'所有'operator(。例如,我想查询与约翰·史密斯(John Smith(相同的课程的教师。

我试图了解为什么我的过程不正确。

select distinct instructor
from testTable
where not exists(
    select course from testTable where not exists (
        select course from testTable where instructor = 'John Smith')
)

我背后的想法是找到所有不是约翰·史密斯(John Smith(教授的课程的课程。

示例输入和输出:

CREATE TABLE testTable (instructor TEXT, course TEXT);
INSERT INTO testTable values ('John Doe', 'Math');
INSERT INTO testTable values ('John Doe', 'English');
INSERT INTO testTable values ('John Doe', 'Physics');
INSERT INTO testTable values ('Jane Doe', 'Math');
INSERT INTO testTable values ('John Smith', 'Physics');
INSERT INTO testTable values ('John Smith', 'Math');
INSERT INTO testTable values ('Janice Smith', 'English');
INSERT INTO testTable values ('Janice Smith', 'Physics');
INSERT INTO testTable values ('James Smith', 'Math');
INSERT INTO testTable values ('James Smith', 'Physics');

输出应为:

James Smith
John Smith
John Doe

一种方法使用自我加入,然后由教师聚集,以检查匹配课程的数量是否与约翰·史密斯(John Smith(的名册一致。

SELECT t1.instructor
FROM testTable t1
INNER JOIN testTable t2
    ON t1.course = t2.course AND
       t2.instructor = 'John Smith'
GROUP BY
    t1.instructor
HAVING
    COUNT(*) = (SELECT COUNT(*) FROM testTable WHERE instructor = 'John Smith');

此答案假设给定的讲师/课程对仅出现一次,而不再重复。如果不是,则需要稍微修改上述查询。

最新更新