In a group project I'm doing (a forum), I'm stuck on the task of sorting forum threads by the last reply. I know the title was somewhat confusing, but we'll try get an understanding of the scenario below.
I have two tables, which have some foreign keys and relation keys, and I want to order the rows selected from the table containing the threads by the newest post with the associated ID for that thread.
The two database tables looks like this:
As you can see above, some of the table keys who should be able to relate to keys in the other table, have different names. Furthermore, I need to link/group/join ForumPost.ThreadID to ForumThread.ID, but all my current efforts have only led me to getting multiple rows for each reply to a thread, meaning that a thread with eg 2 replies would show up twice after sorting the result.
Here is what I have tried so far:
Attempts at sorting thread by last post:
SELECT DISTINCT ForumPost.ThreadID,
ForumThread.*
FROM ForumThread
LEFT JOIN ForumPost
ON ForumThread.ID = ForumPost.ThreadID
GROUP BY ForumPost.ThreadID
ORDER BY ForumPost.CreationDate DESC,
ForumThread.ID DESC
LIMIT $offset, 10
SELECT ForumThread.*
FROM ForumThread
LEFT JOIN ForumPost
ON ForumThread.ID = ForumPost.ThreadID
GROUP BY ForumPost.ThreadID,
ForumThread.ID
ORDER BY ForumPost.CreationDate DESC,
ForumThread.ID DESC
LIMIT $offset, 10
SELECT DISTINCT ForumThread.*
FROM ForumThread
INNER JOIN ForumPost
ON ForumThread.ID = ForumPost.ThreadID
GROUP BY ForumThread.ID
ORDER BY ForumPost.CreationDate DESC,
ForumThread.ID DESC
LIMIT $offset, 10
Original simple query:
SELECT *
FROM ForumThread
ORDER BY ID DESC
LIMIT $offset, 10
Would you in this case just recommend grabbing the information separately, and use a language such as PHP (obviously this is what we're using for this project) to associate the two different MySQL results and sort them then, or do you have a faster and more compact solution?
Note; For all those of you who recommend me to use MySQLi, I can confirm that my group have pondered whether to use MySQLi or MySQL, though our learning pensum have only covered the outdated MySQL material, making it weight out the possibility for learning MySQLi with our narrow deadline for this project.
This is a possibility using a correlated subquery; hope it helps
SELECT
ForumThread.id, Title,
(SELECT MAX(CreationDate) FROM ForumPost
WHERE
ForumPost.ThreadID = ForumThread.id) AS lastentry
FROM ForumThread group by 1, 2 order by 3 desc;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.