I am creating a small message board and I am stuck
I can select the subject, the original author, the number of replies but what I can’t do is get the username, topic or date of the last post.
There are 3 tables, boards, topics and messages.
I want to get the author, date and topic of the last message in the message table. The author and date field are already fields on the messages table but i would need to join the messages and topics table on the topicid field.
this is my query that selects the subject, author, and number of replies
SELECT t.topicname, t.author, count( message ) AS message FROM topics t INNER JOIN messages m ON m.topicid = t.topicid INNER JOIN boards b ON b.boardid = t.boardid WHERE b.boardid = 1 GROUP BY t.topicname
Can anyone please help me get this finished?
This is what my tables look like
CREATE TABLE `boards` ( `boardid` int(2) NOT NULL auto_increment, `boardname` varchar(255) NOT NULL default '', PRIMARY KEY (`boardid`) ); CREATE TABLE `messages` ( `messageid` int(6) NOT NULL auto_increment, `topicid` int(4) NOT NULL default '0', `message` text NOT NULL, `author` varchar(255) NOT NULL default '', `date` timestamp(14) NOT NULL, PRIMARY KEY (`messageid`) ); CREATE TABLE `topics` ( `topicid` int(4) NOT NULL auto_increment, `boardid` int(2) NOT NULL default '0', `topicname` varchar(255) NOT NULL default '', `author` varchar(255) NOT NULL default '', PRIMARY KEY (`topicid`) );
if your SQL supports the LIMIT clause,
otherwise:
EDIT: if you want to combine this with the original query, it has to be rewritten using subqueries to extract the message count and the date of last message:
also notice that if you don’t pick any field from table boards, you don’t need the last join:
EDIT: if mysql doesn’t support subqueries in the field list, you can try this: