帮助将SQL嵌套子查询转换为连接查询以实现mysql 4.0兼容性

时间:2010-11-11 21:13:56

标签: sql mysql left-join self-join nested-queries

我有一个嵌套的SQL查询:

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

我的网络服务器运行MySQL 4.0,它不允许嵌套查询。一些SQL大师可以使用JOIN术语建议相同的查询吗?我尝试过并试过......但我无法弄清楚这一点。感到愚蠢。

2 个答案:

答案 0 :(得分:2)

假设topic_id不可为空,您可以这样做:

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

答案 1 :(得分:1)

我不太确定你的要求是什么,但通过查看你的查询,我认为这应该足够了。

SELECT DISTINCT(topic_id) 
FROM bb_posts 
WHERE poster_id <> $user_id OR post_status <> 0 
ORDER BY post_time DESC