Friday, March 23, 2012

Joining Two Tables

I've been trying to think about how I can do this. I have forums that I have written built around SQL Server. Basicly you have:

-A users Table
-A Posts Table
-A Replies Table.

Posts and replies have very similar structures. I'd like to be able to merge them and pick out the earliest post for said forum.

1 - is there a way to merge them so that the post date for both the replies and posts tables is contained in 1 column. If not is there a better alternative.

I'd also like to add indexing to the posts so I can do paging. Is there a way for me to add an index number to them while I can sort them anyway i want.Yes. You can use the UNION operator to create the reultset you are looking for. See BOL for details, but basically:

SELECT UserID, PostTitle AS Title, PostDate AS PostDate
FROM Posts
WHERE UserID = @.UserID

UNION

SELECT UserID, ReplyTitle AS Title, ReplyDate AS PostDate
FROM Replies
WHERE UserID = @.UserID

ORDER BY PostDate DESC

(...or something along those lines; haven't UNIONed in quite a while...)sql

No comments:

Post a Comment