您如何制作一条SQL语句,该语句返回由子查询或联接或其他内容修改的结果,以处理您要返回的信息?

例如:

CREATE TABLE bowlers (
bowling_id int4 not null primary key auto_increment,
name text,
team text
);

某人可能不正确地在多个团队中:
INSERT INTO `bowlers` (`name`, `team`) VALUES
('homer', 'pin pals'),
('moe', 'pin pals'),
('carl', 'pin pals'),
('lenny', 'pin pals'),
('homer', 'The homer team'),
('bart', 'The homer team'),
('maggie', 'The homer team'),
('lisa', 'The homer team'),
('marge', 'The homer team'),
('that weird french guy', 'The homer team');

因此homer无法决定他的团队,所以他俩都在。 h!

我想知道the homer team团队之外的所有人,pin pals。我能做的最好的事情是:
SELECT a.name, a.team
    FROM bowlers a where a.team = 'The homer team'
    AND a.name
    NOT IN (SELECT b.name FROM bowlers b WHERE b.team = 'pin pals');

导致:
+-----------------------+----------------+
| name                  | team           |
+-----------------------+----------------+
| bart                  | The homer team |
| maggie                | The homer team |
| lisa                  | The homer team |
| marge                 | The homer team |
| that weird french guy | The homer team |
+-----------------------+----------------+
5 rows in set (0.00 sec)

您知道哪一个很棒!

性能将受到影响,因为将对查询的每个结果(即从B到A到D的)运行子查询。对于几行很大,而对于数十万行来说则很糟糕。

有什么更好的方法?我主要是想通过自我加入来解决问题,但是我不能全神贯注于如何做到这一点。

还有其他方法可以不使用NOT IN( SELECT ... )来执行此操作吗?

另外,这种类型的问题的名字是什么?

最佳答案

像这样:

SELECT a.name, a.team
FROM bowlers a
LEFT OUTER JOIN bowlers b ON a.name = b.name AND b.team = 'pin pals'
WHERE a.team = 'The homer team'
AND b.name IS NULL;

您也可以这样:
SELECT a.name, a.team
FROM bowlers a
WHERE a.team = 'The homer team'
AND NOT EXISTS (SELECT * FROM bowlers b
    WHERE b.team = 'pin pals'
    AND a.name = b.name
    );

顺便说一句,这被称为“左半反连接”。

10-04 16:00