So I’m trying to build a simple forum. It’ll be a list of topics in descending order by the date of either the topic (if no replies) or latest reply. Here’s the DB structure:
forum_topic
id, name, email, body, date
forum_reply
id, email, body, date, topic_id
The forum itself will consist of an HTML table with the following headers:
Topic, Last Modified, # Replies
What would the query or queries look like to produce such a structure? I was thinking it would involve a cross join, but not sure… Thanks in advance.
First off, it seems to me noboody is actually answering your question, which was:
with a requested structure of
Topic, LastModified, # Replies.
The SQL to produce a result table with that structure, given the table structures you provided, would be:
(sorry, this is tested only on SQL Server, as I don’t have access to MySql at the moment)
Also, your structure IS already normalized. Suggestions to the contrary are making assumptions about what you want to do, e.g., assuming that you are interested in tracking user names in addition to email addresses. This is quite reasonable, but is nevertheless an assumption. There is nothing wrong, from a normalization perspective, with using email address as a unique user identifier.
Now, if you are looking for general suggestions on how to set up a database, we can give you LOTS of those. Before normalization, I would start with not using potential keywords as object names (e.g., don’t give columns names like ‘Name’ and ‘Date’).
Regarding the comment from Matt about the value being NULL when there are no replies: using the COALESCE() function will fix that. COALESCE() returns the first non-NULL argument (or NULL if all arguments are NULL). So replace the MAX(r.Date) with MAX(COALESCE(r.Date, t.Date)).