Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

mysql quickie

Options
  • 30-09-2006 11:08am
    #1
    Registered Users Posts: 648 ✭✭✭


    Hi

    i have 2 tables

    blog and comments,

    how do i get a listing of the blogs with a count of the comments on each blog using one mysql statement?
    (ive tryed a few to no avail)

    Tnx


Comments

  • Registered Users Posts: 68,317 ✭✭✭✭seamus


    Try.....

    "SELECT blog.*, count(comments.id) from BLOG
    LEFT JOIN comments on comments.blogid = blog.id
    GROUP BY comments.blogid"

    Shot in the dark, but I think it's in the direction you want to go.


  • Registered Users Posts: 648 ✭✭✭ChicoMendez


    seamus wrote:
    Try.....

    "SELECT blog.*, count(comments.id) from BLOG
    LEFT JOIN comments on comments.blogid = blog.id
    GROUP BY comments.blogid"

    Shot in the dark, but I think it's in the direction you want to go.

    Thanks.. now just to conplicate things..
    the comment table is used for BLOGS and IMAGES and OTHER therefore i need to add a clause like WHERE comment.type=2 (2 is for blogs!)

    however that will only return the blogs with comments....
    any ideas?

    TNX


  • Registered Users Posts: 68,317 ✭✭✭✭seamus


    It may be possible to do using nested queries. What version of MySQL are you running?


  • Registered Users Posts: 648 ✭✭✭ChicoMendez


    seamus wrote:
    It may be possible to do using nested queries. What version of MySQL are you running?


    4.1.9


    TNX


  • Registered Users Posts: 68,317 ✭✭✭✭seamus


    OK, this may need a little tweaking to get right/debugged

    SELECT blog.*, blogdetails.blogcount
    FROM blog
    LEFT JOIN (SELECT sqc.blogid, count(sqc.id) as blogcount
    FROM comment sqc
    WHERE sqc.type = 2
    GROUP BY sqc.id) blogdetails ON blogdetails.blogid = blog.id


  • Advertisement
Advertisement