Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

mysql quickie

  • 30-09-2006 11:08AM
    #1
    Registered Users, Registered Users 2 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, Registered Users 2 Posts: 68,173 ✭✭✭✭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, Registered Users 2 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, Registered Users 2 Posts: 68,173 ✭✭✭✭seamus


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


  • Registered Users, Registered Users 2 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, Registered Users 2 Posts: 68,173 ✭✭✭✭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