SQL Query Help

Duplicate:

How to choose Select aa Select

I have 2 tables:

TABLE1 Table1Id TABLE2 Table2Id Table1Id UserId 

TABLE2 contains thousands of records. I want to return a list of TABLE1 entries, where there is no entry in TABLE2 for it for a specific user. So, if there is no foreign key entry in table 2. Type request:

 select count(*) from TABLE1 where Table1Id not in ( select Table1Id from TABLE2 where id_user = 1) 

However, this query is very slow. What will be the most effective way to get the desired results?

+1
sql tsql
Apr 17 '09 at 16:07
source share
4 answers

There is a similar question

I think it would be better

 SELECT COUNT(*) FROM TABLE1 WHERE NOT EXISTS (SELECT Table1Id FROM TABLE2 WHERE TABLE2.Table1Id = TABLE1.Table1Id AND UserID = 1) 

I would also check the indices as ck suggested

+4
Apr 17 '09 at 16:10
source share

What about

 select Table1Id from TABLE1 minus select Table1Id from TABLE2 where id_user = 1 

I am not sure that MsSql supports minus. If not, you should try a correlated subquery.

+1
Apr 17 '09 at 16:16
source share

You can also use the "EXCEPT / MINUS" intersection to get only the differences between the two tables if the selection returns the same field types / order.

 SELECT TABLE1ID FROM TABLE1 EXCEPT -- or MINUS in Oracle SELECT TABLE1ID FROM TABLE2 WHERE USER_ID = 1 
+1
Apr 17 '09 at 16:17
source share

See How to choose Select aa Select

Also, make sure that all the fields you request have a suitable index.

-one
Apr 17 '09 at 16:09
source share



All Articles