Table1 (id, name) Table2 (id, name)
查询:
SELECT name
FROM table2
-- that are not in table1 already
Table1 (id, name) Table2 (id, name)
查询:
SELECT name
FROM table2
-- that are not in table1 already
当前回答
我没有足够的代表点数来给froadie的答案投票。但我不同意对克里斯回答的评论。以下答案:
SELECT name
FROM table2
WHERE name NOT IN
(SELECT name
FROM table1)
在实践中效率更高。我不知道为什么,但我对800k+的记录进行了运行,上面发布的第二个答案的优势是巨大的。只有我的0.02美元。
其他回答
我将在正确答案....中转发(因为我还没有酷到可以评论)以防有人觉得需要更好的解释。
SELECT temp_table_1.name
FROM original_table_1 temp_table_1
LEFT JOIN original_table_2 temp_table_2 ON temp_table_2.name = temp_table_1.name
WHERE temp_table_2.name IS NULL
在mySQL中,我看到FROM中的语法需要在表名之间使用逗号,但在sqlLite中,它似乎更喜欢空格。
底线是,当你使用不好的变量名时,它会留下问题。我的变量应该更有意义。应该有人解释一下为什么我们需要逗号或不需要逗号。
你可以在mssql中使用EXCEPT或在oracle中使用MINUS,它们是相同的:
http://blog.sqlauthority.com/2008/08/07/sql-server-except-clause-in-sql-server-is-similar-to-minus-clause-in-oracle/
你可以使用以下查询结构:
SELECT t1.name FROM table1 t1 JOIN table2 t2 ON t2。Fk_id != t1.id;
表1:
id | name |
---|---|
1 | Amit |
2 | Sagar |
表二:
id | fk_id | |
---|---|---|
1 | 1 | amit@ma.com |
输出:
name |
---|
Sagar |
小心陷阱。如果表1中的字段Name包含null,你就会感到惊讶。 更好的是:
SELECT name
FROM table2
WHERE name NOT IN
(SELECT ISNULL(name ,'')
FROM table1)
我尝试了以上所有的解决方案,但它们都不适合我。下面的查询对我有用。
SELECT NAME
FROM table_1
WHERE NAME NOT IN
(SELECT a.NAME
FROM table_1 AS a
LEFT JOIN table_2 AS b
ON a.NAME = b.NAME
WHERE any further condition);