我一直在使用以下 SQL:
SELECT DISTINCT NAME
FROM Events t1
LEFT JOIN UserHistory t2 ON t1.Name = t2.Event
WHERE t2.Event IS NULL
从表 1 中选择表 2 为空的所有行。这有效地过滤掉了表 2 有数据的所有表 1 数据。但是,我只想在表 2 中的列等于某个值时应用它。因此,我想做一个SELECT * FROM t2 WHERE t2.ID = 1
但不确定这如何适合这个查询。
SELECT DISTINCT NAME
FROM Events t1
LEFT JOIN UserHistory t2 ON t1.Name = t2.Event and t2.certain_column = 1234
WHERE t2.Event IS NULL
Also you can try query with NOT EXISTS:
SELECT DISTINCT NAME
FROM Events t1
WHERE NOT EXISTS(SELECT * FROM UserHistory t2
WHERE t1.Name = t2.Event AND t2.ID = 1)
您需要将谓词添加到 JOIN 条件:
SELECT DISTINCT NAME
FROM Events t1
LEFT JOIN UserHistory t2 ON t1.Name = t2.Event AND t2.ID = 1
WHERE t2.Event IS NULL;
如果您将其添加到WHERE
您有效地将外部联接转换为内部联接,这意味着不会返回任何行(因为NULL = 1
计算结果为 false)