Question

I have a nested SQL query :

SELECT DISTINCT(topic_id)
FROM bb_posts 
WHERE topic_id NOT IN ( 
  SELECT topic_id FROM bb_posts 
  WHERE poster_id = $user_id AND post_status = 0 ) 
ORDER BY post_time DESC

My webserver runs MySQL 4.0 which doesnt allow nested queries. Can some SQL guru suggest the same query using the JOIN lingo? i tried and tried and tried... but i can't figure this out. Feeling dumb.

Was it helpful?

Solution

Assuming that topic_id is not nullable, you can do:

SELECT DISTINCT(T1.topic_id)
FROM bb_posts As T1
    Left Join bb_posts As T2
        On T2.topic_id = T1.topic_id
            And T2.poster_id = $user_id
            And T2.post_status = 0
Where T2.topic_id Is Null
ORDER BY T1.post_time DESC

OTHER TIPS

I am not quite sure what your requirement is but by looking at your query I think this should suffice.

SELECT DISTINCT(topic_id) 
FROM bb_posts 
WHERE poster_id <> $user_id OR post_status <> 0 
ORDER BY post_time DESC
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top