Showing posts with label built. Show all posts
Showing posts with label built. Show all posts

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

Wednesday, March 21, 2012

joining two results

I have two sets of results built up. Each set has a state value. Although one set has 38 states in the results while the other has 23. Is it possible to join these sets and show a result for each of the 38 states even if there is not a corresponding value in the other set. All attempts I've made lose the 15 states that do not appear in the other set. Any help would be great. Thanks in advanceIf your database engine supports LEFT JOIN, or better yet FULL JOIN, then you are in business. If not, you can kind of "fake it" using a sub-select, but it is hokey.

-PatP