开发者

DELETE FROM query with JOINs not working?

I have the following MySQL query, which I'm using with PHP (5.2).

DELETE t1.*, t3.* FROM 
            forum_posts AS t1,
            forum_topics AS t2,
            user_points AS t3
WHERE  t1.topic_id = t2.topic_id
       AND t2.deleted = 1
       AND t1.post_id = t3.id
       AND t3.type = 'post'
       AND t1.post_author = t3.profile_author  

However it's not functioning how I'm intending it too (nothing happens!), let me explain:

What I intend the query to be doing is to delete all rows in the forum_posts table and/or (I'm saying "and/o开发者_如何学Gor" because it will depend if the rows even exist) delete all rows in the user_points table => [if the topic in which the post was created has been deleted (for your info to avoid confusion it's really just "hidden", we determine this by checking if it equals 1)].

I hope the query structure explains it self, the topic_id is mainly used to JOIN the the tables together.

The query runs fine (gives no MySQL or PHP errors, so I would assume the syntax is fine?), I've checked the DB and theres topics which exist which are deleted (the deleted column is set to 1) and theirs post which exist aswell for those topics (so it's not the case that there is no data).

Appreciate all replies.


I have a personal preference of always specifying the joins explicitly instead of lumping everything in the where clause. This also helps in visualizing where you might need a LEFT join.

DELETE forum_posts t1, user_points t3
    FROM forum_posts AS t1
    INNER JOIN forum_topics AS t2 ON t2.topic_id = t1.topic_id
    INNER JOIN user_points AS t3 ON t3.id = t1.post_id
        AND t3.profile_author = t1.post_author
        AND t3.type = 'post'
WHERE t2.deleted = 1

Now, based on your statement, I'd suggest changing the second INNER JOIN to a LEFT JOIN:

DELETE forum_posts t1, user_points t3
    FROM forum_posts AS t1
    INNER JOIN forum_topics AS t2 ON t2.topic_id = t1.topic_id
    LEFT JOIN user_points AS t3 ON t3.id = t1.post_id
        AND t3.profile_author = t1.post_author
        AND t3.type = 'post'
WHERE t2.deleted = 1

I hope that helps!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜