views:

47

answers:

6

table 1: id1, name, surname

table 2: id1, id2, value

id1 is a foreign key for table 2

What is the fastest query to find the table 1 records that do not have a record in table 2 with value = c ?

Can you please help me?

+1  A: 

You can use NOT IN or NOT EXISTS. Here is a functionality comparative website.

Ardman
A: 
select * from table1 as tb1
where tb1.id1 not in 
  (select tb2.id1 from table2 as tb2
   where tb1.id1 = tb2.id1
     and value='c')

Depends of course largely on the sizes of table1 and table2, but I've found that inner queries are a lot more efficient than I originally assumed through testing.

Neil
+1  A: 

In general circumstances query is doomed to be slow.

select * from table1 where not exists 
  ( select id1 from table2 where table1.id1 = table2.id2 and value = с )
maxim_ge
I'd be inclined to go with the EXISTS route too. However, I don't agree that it's doomed to be slow - as long as there are suitable indexes, it should be fine.
AdaTheDev
A: 

This query will give you all records in Table 1 that either

  1. Do not have records in table 2.

  2. Do not have records in table 2 with value = 'c'

:

SELECT * 
FROM table1 
WHERE id1 NOT IN 
    (SELECT id1 FROM table2 WHERE value = 'c')

This query will give you all records in Table 1 that either

  1. Do HAVE records in table 2.

  2. BUT do not have records in table 2 with value = 'c'

:

SELECT * 
FROM table1 t1
INNER JOIN table2 t2
ON t1.id1 = t2.id1
WHERE t1.id1 NOT IN 
    (SELECT id1 FROM table2 WHERE value = 'c')
InSane
A: 

You might try this solution,

WITH MISSING (id1)
AS
(
SELECT id1 FROM table1
EXCEPT
SELECT distinct id1 FROM table2 WHERE value = 'c'
)
SELECT * FROM table1 t inner join MISSING m on t.id1 = m.id1;
-- or
SELECT * FROM table1 t WHERE EXISTS (SELECT id1 FROM MISSING m WHERE t.id1 = m.id1);
Vash