views:

39

answers:

2

I've spent a whole day on this already without figuring it out. I'm hoping somebody can help me translate the following MySQL query to work for SQL Server 2005:

SELECT MAX ( messages.date ) AS maxdate,  
topics.id AS topicid, topics.*, users.*  
FROM messages, topics, users WHERE messages.topic_id  
= topics.id AND topics.user_id = users.id AND  
topics.forum_id = " . $forumid . " GROUP BY  
messages.topic_id ORDER BY maxdate DESC

$forumid is a QueryString value defined in the following VB.NET code-behind code:

forumName.Text = "<a href='ViewForum.aspx?forumid=" & row.id & "'>" & row.name & "</a>"

I'd be super grateful if u can help.

+1  A: 

SQL Server doesn't allow you to reference column aliases in an order by (at least, 2005 didn't.) If you replace the order by with:

ORDER BY MAX ( messages.date )

You should be one step closer to a working SQL Server 2005 query.

Andomar
+1  A: 

There are two problems. Firstly, as Andomar pointed out, you cannot refer to column aliases in the ORDER BY.

Secondly, if you are performing aggregation (like the MAX) you cannot select any fields that are not in the GROUP BY unless they are aggregated too.

I think this is what you want:

SELECT m.maxdate, t.*, u.*
FROM (
    SELECT topic_id, MAX(messages.date) AS maxdate
    FROM messages
    GROUP BY topic_id
) AS m
    INNER JOIN topics t ON t.id = m.topic_id
    INNER JOIN users u ON t.user_id = u.id
WHERE t.forum_id = " . $forumid . "
ORDER BY m.maxdate DESC
Paul
That works!! Thank you so much.
brookmarker