DotDragnet
May 24, 2012, 05:53:07 AM *
Welcome, Guest. Please login or register.

Login with username, password and session length
News: Mobile users - Our forum is Tapatalk enabled. http://www.tapatalk.com/
 
   Home   Help Search Login Register  
Pages: [1]   Go Down
  Print  
Author Topic: [SOLVED] Retrieving All Threads And First Posts  (Read 208 times)
Dom
Hero Member
*****
Posts: 1681


Taster of pasities. Clanger of both pots AND pans.


DominicNeagle
View Profile Awards
« on: August 02, 2011, 11:37:45 AM »

Hi all,

I've been given the "simple, five minute" task of building some basic forum/bulletin board software. But I'm having trouble building the page that shows users all the threads.

What I need is a page that shows all the current threads (well, the top 10 most recent actually, but that's not the hard part right now). I need the page to display the thread title, and the first post in the thread.

What I have is two SQL Server 2005 tables: one table stores the thread info, and the other table stores into about each post. They look like so:



The Posts table has a foreign key (InReplyToThreadID) which links to the 'ThreadID' in the Threads table. That's how the posts are related to the threads.

There can be lots of posts for any given thread, but what I need is a single SQL query (using T-SQL) that gives me all thread titles, and then the first post of each of the threads.

I've not really used anything much more complicated than JOINS in SQL queries, so I'm a bit stuck. I can join the tables, but any query I write seems to return either the thread titles with the very latest post (that doesn't match the threads) or it returns every post and associated thread title, so I get rows with repeated titles.

Anyone know how to get just the thread title and first post of that thread, for all threads?
« Last Edit: August 02, 2011, 02:00:48 PM by Dom » Logged

Dom
Hero Member
*****
Posts: 1681


Taster of pasities. Clanger of both pots AND pans.


DominicNeagle
View Profile Awards
« Reply #1 on: August 02, 2011, 02:00:30 PM »

Got the shizzle working, with a lot of help from peeps on Twitter:

Code:
SELECT tblBulletinBoardThread.ThreadID,
tblBulletinBoardThread.ThreadTitle,
tblBulletinBoardPost.PostText
FROM tblBulletinBoardPost
INNER JOIN tblBulletinBoardThread 
ON tblBulletinBoardThread.ThreadID = tblBulletinBoardPost.InReplyToThreadID
WHERE PostID IN
(SELECT MIN(PostID) AS 'PostID'
FROM tblBulletinBoardThread
INNER JOIN tblBulletinBoardPost
ON tblBulletinBoardThread.ThreadID = tblBulletinBoardPost.InReplyToThreadID
GROUP BY ThreadID)
ORDER BY tblBulletinBoardPost.DateTimePosted DESC;
Logged

Pages: [1]   Go Up
  Print  
 
Jump to:  

Powered by MySQL Powered by PHP Powered by SMF | SMF © 2006-2008, Simple Machines Valid XHTML 1.0! Valid CSS!