没有聚合或子查询的查询

Posted

技术标签:

【中文标题】没有聚合或子查询的查询【英文标题】:Queries without Aggregate or SubQuery 【发布时间】:2018-02-21 00:38:10 【问题描述】:

我想知道是否有可能找到所有教“数学”但不教“英语”的教师,不使用聚合子查询。

我的常规方法是通过查找所有教授英语并使用的子查询/聚合:其中教师不在(从课程中选择教师,其中课程 = '英语')或按教师分组,课程具有计数(*) > 1.

//下面测试输入输出

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');

解决办法应该是:

Jane Doe

John Smith

【问题讨论】:

使用聚合和子查询有什么问题?您的“正常方法”是否由于某种原因不起作用? 有人告诉我要避免使用子查询,所以我正在尝试学习其他解决此类问题的方法,其中通常的方法是使用子查询/聚合。 【参考方案1】:

您可以使用joins 来做到这一点

select tm.instructor
from t tm left join
     t te
     on tm.instructor = te.instructor and te.subject = 'English'
where tm.subject = 'Math' and te.instructor is null;

【讨论】:

以上是关于没有聚合或子查询的查询的主要内容,如果未能解决你的问题,请参考以下文章