I'm writing code to hit a tree structure which is persisted in a MySQL database, each node storing the ID of its parent or NULL if it's the root of the tree. In the course of querying it to try to get all leaf nodes, I noticed something odd.
Namely, this query produces no results:
SELECT *
FROM tree_table
WHERE node_id NOT IN(SELECT parent_node_id FROM tree_table)
while this one produces the results I'm after:
SELECT *
FROM tree_table
WHERE node_id NOT IN(
SELECT node_id
FROM tree_table
WHERE node_id IN(SELECT parent_node_id FROM tree_table))
It seems to be the NOT that's giving me the trouble. Is this something about order of operations or similar that I'm misremembering?