I feel totally stupid. I’m rusty with my sql.
I have two tables, Message and MessageThread. Each message belongs to one MessageThread using ParentTHreadID as a Foreign Key. You probably can see where this is going.
Well, I want to do something like this. I want to get columns from both tables, messages and threads, but where the message’s datecreated is the maximum in that thread. So each record will contain the thread columns and the columns for one message record that is the most recent posted in that message thread.
Here is what I have so far which gets me all the thread columns and the ID of the message. It works, but uses a subquery and I’d have to make a bunch of other subqueries to get the other columns. Yuck.
select t.*,
(select top 1 m.ID
from Message m
where m.ParentThreadID = t.ID
order by DateCreated desc ) as MessageID
from MessageThread t
Bonus points to anyone who can not only give me sql, but linq to sql or linq to nhibernate.
Thanks,
Craig
The solution: more subqueries!!
This should get you all the columns with two nested queries.