How to select all records from one table that do n

2019-01-02 16:20发布

table1 (id, name)
table2 (id, name)

Query:

SELECT name   
FROM table2  
-- that are not in table1 already

10条回答
笑指拈花
2楼-- · 2019-01-02 16:55

I don't have enough rep points to vote up the 2nd answer. But I have to disagree with the comments on the top answer. The second answer:

SELECT name
FROM table2
WHERE name NOT IN
    (SELECT name 
     FROM table1)

Is FAR more efficient in practice. I don't know why, but I'm running it against 800k+ records and the difference is tremendous with the advantage given to the 2nd answer posted above. Just my $0.02

查看更多
无色无味的生活
3楼-- · 2019-01-02 16:56

Watch out for pitfalls. If the field Name in Table1 contain Nulls you are in for surprises. Better is:

SELECT name
FROM table2
WHERE name NOT IN
    (SELECT ISNULL(name ,'')
     FROM table1)
查看更多
琉璃瓶的回忆
4楼-- · 2019-01-02 16:56

I'm going to repost (since I'm not cool enough yet to comment) in the correct answer....in case anyone else thought it needed better explaining.

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

And I've seen syntax in FROM needing commas between table names in mySQL but in sqlLite it seemed to prefer the space.

The bottom line is when you use bad variable names it leaves questions. My variables should make more sense. And someone should explain why we need a comma or no comma.

查看更多
墨雨无痕
5楼-- · 2019-01-02 16:58

Here's what worked best for me.

SELECT *
FROM @T1
EXCEPT
SELECT a.*
FROM @T1 a
JOIN @T2 b ON a.ID = b.ID

This was more than twice as fast as any other method I tried.

查看更多
ら面具成の殇う
6楼-- · 2019-01-02 17:09

That work sharp for me

SELECT * 
FROM [dbo].[table1] t1
LEFT JOIN [dbo].[table2] t2 ON t1.[t1_ID] = t2.[t2_ID]
WHERE t2.[t2_ID] IS NULL
查看更多
柔情千种
7楼-- · 2019-01-02 17:10

You can use EXCEPT in mssql or MINUS in oracle, they are identical according to :

http://blog.sqlauthority.com/2008/08/07/sql-server-except-clause-in-sql-server-is-similar-to-minus-clause-in-oracle/

查看更多
登录 后发表回答