标签:
Do you use the following syntax?
OR this?
Do NOT use that, it will cause problems sooner or later. Don‘t believe me? Let‘s take a look
First create these 2 tables and populate them with some sample data
Now let‘s run the IN query
id1 |
1 |
2 |
No problems here right?
What if by mistake you wrote id1 instead of id2?
id1 |
1 |
2 |
3 |
Oops all 3 rows are returned, if you just run this SELECT id1 FROM TestTable2 you will get this error
Server: Msg 207, Level 16, State 3, Line 1
Invalid column name ‘id1‘.
So what happens? SQL Server sees column id1 and says "yes I have that it is in the TestTable1 table, I can use that" What can we do? Use EXISTS because you will get an error instead of a wrong resultset
id1 |
1 |
2 |
A JOIN will do the same as EXISTS
id1 |
1 |
2 |
Now let‘s try NOT IN
id1 |
3 |
No problem right?
Add a NULL value to the TestTable2 table
Let‘s try running it again
Where are my rows? Nowhere, since NULL is not equal to anything including another NULL SQL just returns nothing
What happens when you use NOT EXISTS?
id1 |
3 |
That works without a problem
What about a LEFT JOIN?
id1 |
3 |
That works without a problem also
So from now on use EXISTS, NOT EXISTS, JOIN and LEFT JOIN
DO NOT use IN or NOT IN ever again!
Subquery typo with using in(转)
标签:
原文地址:http://www.cnblogs.com/qook/p/4914111.html