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
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

SQL Help

  • 05-07-2008 3:54pm
    #1
    Registered Users, Registered Users 2 Posts: 872 ✭✭✭


    Hi,

    I have a posts table and a replies table. I want to be able to count the number of replies that relate to each post and output them on the front end....

    Table Posts
    post_id
    title
    body

    Table Replies
    reply_id
    name
    email
    post_id

    So the tables are linked with post_id.

    When i am displaying all the active posts on the front end i do

    SELECT title,body FROM Posts

    How can i count the number of rows in Replies that relate to the current row being selected.

    I was thinking of some table variable but i think im making it really complicated for myself.

    Thanks for any advice


Comments

  • Closed Accounts Posts: 317 ✭✭tiptap


    select post_id, count(post_id) from tblReplies
    group by post_id

    Will that work for you,
    you will know how many entries you have for each post


  • Registered Users, Registered Users 2 Posts: 2,152 ✭✭✭dazberry


    Something like this might do it for you... wouldn't be a top SQL person myself...

    select p.post_id, count(r.*) from posts p, replies r
    where p.post_id = r.post_id
    group by 1
    union
    select p.post_id, 0 from posts p
    left outer join replies r on (r.post_id = p.post_id)
    where r.post_id is null

    D.


  • Closed Accounts Posts: 3,357 ✭✭✭Beano


    When posting questions asking for help on SQL you should really say what flavour of SQL you are using.

    select p.post_id, count(distinct r.reply_id)
    from posts p
    left join replies r
    on p.post_id = r.post_id

    should do the trick for you.


  • Registered Users, Registered Users 2 Posts: 872 ✭✭✭grahamor


    Thanks alot guys for the informative replies.

    I knew it was easier than the way i was planning on doing it.


Advertisement