tags:

views:

570

answers:

8

I have a table containing a unique ID field. Another field (REF) contains a reference to another dataset's ID field. Now I have to select all datasets where REF points to a dataset that doesn't exist.

SELECT * FROM table WHERE ("no dataset with ID=REF exists")

How can I do this?

A: 
SELECT * 
FROM table 
WHERE ((SELECT COUNT(*) FROM table2 WHERE table2.id = table.ref) = 0)
antonioh
hahaha! -2 points, I'm glad at least the code works even if it's not the neatest, otherwise who knows how many points less!
antonioh
+4  A: 

I think this should work

SELECT * FROM table WHERE id NOT IN (SELECT ref_id FROM ref_table)

or with JOIN

SELECT table.* 
FROM table LEFT JOIN ref_table ON table.id = ref_table.ref_id
WHERE ref_table.ref_id IS NULL
Jhonny D. Cano -Leftware-
won't work if you have NULL values
SQLMenace
+2  A: 

You can do a subquery like:

select * from table where somefield not in (select otherfield from sometable where ID=REF)
Alex Fort
you can't do somefield in (select *... as one field cannot evaluate to many
ck
+5  A: 

Try this:

SELECT * FROM TABLE WHERE NOT EXISTS 
     (SELECT * FROM OtherTable WHERE TABLE.Ref = OtherTable.ID)
ck
Table.ref = othertable.id
Jimmy
A: 

Something like that :

SELECT * FROM table WHERE ID NOT IN(SELECT REF FROM Table2 )
Canavar
+3  A: 
SELECT 
 table1.* 
FROM 
 table1
 LEFT JOIN table2 ON table1.id = table2.ref
WHERE 
 table2.ref IS NULL
Jose Basilio
SELECT Table1.*..
ck
+1, JOINs are preferable to sub-selects most of the time.
Matt Grande
+1  A: 

yo dawg i herd u liek selects so we put a select in ur select so you can query while you query.

Matt Grande
I heard you like comments in your selects, so I put a comment in your select so you select your comments while comment on your selects
Brian
probably shouldn't be here, but it's really funny IMO.
Jeff Atwood
+19  A: 

3 ways

SELECT * FROM YourTable y WHERE NOT EXISTS 
     (SELECT * FROM OtherTable o WHERE y.Ref = o.Ref)

SELECT * FROM YourTable WHERE Ref NOT IN 
     (SELECT Ref FROM OtherTable WHERE Ref IS NOT NULL)

SELECT y.* FROM YourTable y 
LEFT OUTER JOIN  OtherTable o ON y.Ref = o.Ref
WHERE o.Ref IS NULL

See also Five ways to return all rows from one table which are not in another table

SQLMenace