tags:

views:

28

answers:

2

Hi, I have a sql query that is retrieving results from a table but I need it to only show results if the ids are not in another table.

Example

$sql = "SELECT id FROM TABLE_1 WHERE id NOT IN(SELECT more_id FROM TABLE_2)

The idea is that if the id does not exist in the list of "more_id" then it should show the result.

It does not seem to work, any help would be greatly appreciated. I should mention that "more_id" is just the same "id" but in another table that stores other records.

+3  A: 

This should work:

$sql = "SELECT TABLE_1.id
            FROM TABLE_1
            LEFT JOIN TABLE_2
                ON TABLE_1.id = TABLE_2.more_id
            WHERE TABLE_2.more_id IS NULL"

Without the WHERE clause, you will end up with a list of all items in TABLE_1, including both the ones with matches in TABLE_2 and those without. Adding the WHERE clause filters the matches out.

Ali
Correct me if I am wrong, isn't this the same as `SELECT id FROM TABLE_1 WHERE id IS NULL`. Doesn't make sense to me.
o.k.w
This should produce the same result set as the OP's query, though, no? (Depending on how the RDBMS uses indexes, however, one *may* be faster than the other, but that's not the original question..)
lc
No, it's not the same. Added a description to explain why.
Ali
@lc I think the original query looks OK as well. Sometimes an alternative is all that is needed.
Ali
@o.k.w: no that fine, it will try to join table 1 and table 2, if there is no matching more_id would be NULL.
RageZ
@Ali, now it makes sense :)
o.k.w
@o.k.w It's a left-join, which says to take all records where the join conditions match and if there are no records matching the join condition to take the left side (TABLE_1 in this case) and set the right side NULL. Thus this query returns all rows where there is no matching TABLE_2 row.
lc
@lc Yep, should be faster. Not the original question, but I can't help but push good SQL practices ;)
Ali
@Ali Very true. Frankly, I've had flaky results with IN before; replacing it with EXISTS or JOIN has fixed the problem. Perhaps it's another example of this...
lc
@To all: Thanks for the explanation, I learnt something new today!
o.k.w
A: 

My best bet is one table is using VARCHAR as id, the other table is using INTEGER,CHAR or other incomparable types.

J-16 SDiZ