1

我一直在使用以下 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但不确定这如何适合这个查询。

4

3 回答 3

3
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
于 2013-11-12T11:30:08.093 回答
2

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)
于 2013-11-12T11:50:03.017 回答
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)

于 2013-11-12T11:30:27.823 回答