Need help with an SQL Query!

Discussion in 'MySQL' started by kuttappan, Jun 22, 2010.

  1. #1
    I need an SQL query or PHP script that will delete attachments from a certain forum. So far the only thing I can somewhat come up with is this query that I slapped together which if MySQL could understand what I was saying then it would work just fine However I must translate this into MySQL's language as obviously it doesn't work as it sits!

    SELECT * FROM `thread` WHERE `forumid` = '25' AS t1
    SELECT * FROM `t1`,`post` WHERE `post.postid` = `t1.postid` AS t2
    SELECT * FROM `t2`,`attachment` WHERE `attachment.postid` = `t2.postid`

    So in the first line I wanna select all rows from the `thread` table WHERE the column `forumid` is = to 25 and then ALIAS this as t1

    The second line SELECT all rows FROM `t1` (which we just created with line 1) and all rows from `post` WHERE `post.postid` = `t1,postid` and ALIAS this as t2

    The third line SELECT all rows FROM `t2` (which we just created with line 2) and also SELECT all rows from `post` WHERE `attachment.postid` = `t2.postid`

    This should now give me my final list of all the attachments that are in posted in forumid 25

    Hope this all makes sense. If you have a better solution which I'm sure you will then that's fine. When it comes down to it all I need to do is DELETE all the attachments that are in a particular forum. This is the somewhat only way I can think to do it.

    Any ideas?
     
    kuttappan, Jun 22, 2010 IP
  2. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #2
    A bunch of JOINS should be a cleaner way of doing this.

    SELECT *
    FROM   attachment
           INNER JOIN thread
             ON attachment.postid = thread.postid
           INNER JOIN post
             ON thread.postid = post.postid
    WHERE  thread.forumid = 25;
    Code (markup):
    Technically, there's no reason you need the post table included in this unless you just need the column data.

    If you need to delete, you can use the same query, altered a bit.

    DELETE attachment.*
    FROM   attachment
           INNER JOIN thread
             ON attachment.postid = thread.postid
           INNER JOIN post
             ON thread.postid = post.postid
    WHERE  thread.forumid = 25;
    Code (markup):
    Make sure to make a backup of all the tables in the query before doing a delete like this.
     
    Last edited: Jun 22, 2010
    jestep, Jun 22, 2010 IP
  3. netload

    netload Member

    Messages:
    105
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    28
    #3
    Maybe you should use LEFT JOIN instead of INNER JOIN (some threads have no posts and some posts have not attachments).
    thread LEFT JOIN post ... LEFT JOIN attachemnt ...

    UPD. Sorry, I read carelessly first post. Of course, INNER JOIN only.
     
    netload, Jun 23, 2010 IP