views:

40

answers:

2

I have a little problem - i would can get with this query topics posts count and last post id, but i can't figure out, how to get right user id. I get first post (lowest id) user id but i want lastest post... I have tried adding "ORDER BY id DESC" but this will not help. Any ideas how to do it?

SELECT 
    COUNT(`id`) AS `count`, 
    MAX(`id`) AS `last_post_id`, 
    `topic_id`, 
    `user_id` 
FROM `forum_posts` 
WHERE `topic_id` IN (326, 207, 251) 
GROUP BY `topic_id` 
A: 

In your query userid returns the userid of any userid in that group, which will typically be the first one that appears in whatever index the optimizer happened to pick, but it does not have to be.

Self-join to fetch the user_id from the row that has the id you are interested in:

SELECT T1.`count`, T1.last_post_id, T1.topic_id, T2.user_id
FROM (
    SELECT 
        COUNT(id) AS `count`,
        MAX(id) AS last_post_id,
        topic_id, 
    FROM forum_posts
    WHERE topic_id IN (326, 207, 251) 
    GROUP BY topic_id
) T1
JOIN forum_posts T2
ON T1.last_post_id = T2.id
Mark Byers
+1  A: 

You should be using ORDER BY on a timestamp that you store in the database when the post is created. This will ensure that you are sorting the posts by time, and not by ID, since ID can be messed up if you delete / add posts.

Chetan
Doesn't stop someone from backdating a column value -- you'd need a CHECK constraint (which means trigger on MySQL) to enforce otherwise.
OMG Ponies
While this is good information it should be a comment, not an answer. It doesn't solve the problem the OP has.
Mark Byers
@Mark: The OP wants to sort posts by time, and this information is one way that has advantages over the way pursued by the OP. That's why I believe it's an answer to his / her question, not just extra information.
Chetan