I have two tables: a Topics tables and a joined Comments tables, both with timestamp columns. I would like to order the topics list so that topics with the most recent comment are at the top. However, if a topic has no comments, I want it to be sorted by the date it was created.
In other words I’m trying to order it so that the topics are sorted by the date they were created only if they have no comments – basically like any forum. For example if topic A (empty) was created after topic B (not empty) but topic B has a reply that was most recent the order should be B, A. I don’t want all the empty topics at the top if they’re old or at the bottom if they’re new.
I tried the IF ISNULL statement but it applies to the entire column and not each individual row so I end up with the empty threads either stuck at the top or bottom of the feed.
I’m guessing I’d have to construct a virtual column with only the most recent comment from each topic…?
Here’s the full statement:
SELECT
$showbody,
Topics.Title,
Topics.id AS tID,
Topics.Timestamp,
Topics.MemberID,
Users.id,
Users.FirstName,
Users.LastName,
GROUP_CONCAT(DISTINCT Tags.Keywords SEPARATOR ', ') AS Tags,
COUNT(Comments.id) AS NumberOfComments,
(
SELECT COUNT(Comments.id)
FROM Comments
LEFT JOIN Views ON Comments.TopicID = Views.TopicID
WHERE Comments.Timestamp > Views.Visited
) AS NewComments
FROM Topics
LEFT JOIN Users ON Topics.MemberID = Users.ID
LEFT JOIN Comments ON Topics.id = Comments.TopicID
LEFT JOIN Tags ON Topics.id = Tags.TopicID
WHERE Topics.id NOT IN (
SELECT Tags.TopicID
FROM Tags
WHERE Keywords IN (
SELECT Tag
FROM Filters
WHERE MemberID = '$_SESSION[SESS_MEMBER_ID]'
)
GROUP BY Tags.TopicID
)
GROUP BY Topics.id
ORDER BY Comments.Timestamp, Topics.Timestamp DESC LIMIT $plim
Any help would be greatly appreciated
Solution 1 (demo):
Results:
Solution 2: