Return 行在另一个 table 中找不到匹配项

Return rows where no match is found in another table

找不到具有此确切问题的问题。

我有 2 个 table,我想 return 一个 table 中的行,而第二个 table 中不存在该行。

我会做一个例子来展示。

第一个table:

团队名称
联合
运动
足球
橄榄球

第二个table:

用户名团队
加里 曼联
加里 曼联
菲尔 橄榄球
菲尔 橄榄球

所以我想做的是 select 第一个 table 中没有出现在第二个 table 中的所有团队。但是问题是我只想让它与用户名为 Gary 的行进行比较。

因此 select 从第一个 table 开始的所有行中,第二个 table 中不存在团队名称,例如用户名是 Gary。

我设法通过左连接拉取第二个 table 中不存在团队名称的所有行,但是我不确定如何添加用户名等于某物的条件。

我意识到我可能必须更改 table 的结构。我愿意接受建议吗?

如果您想查找所有没有名为 Gary 的球员的球队,请使用 left outer join:

select t.*
from teams t left join
     userteams ut
     on t.teamname = ut.teamname and ut.name = 'Gary'
where ut.username is null;

使用 NOT EXISTS 子句查找 table2

中不存在的球队
SELECT t.*
FROM   teams t
WHERE  NOT EXISTS (SELECT 1
                   FROM   userteams ut
                   WHERE  t.teamname = ut.teamname
                          AND ut.name = 'Gary')