我正在使用 PHP 和 MySQL 编写一个简单的论坛。
在论坛主页上,我想按字母顺序列出所有主题,并且我想为每个主题显示最新的帖子以及发帖人的用户名。
我知道如何对线程表进行排序,我知道如何从帖子表中提取给定线程的最新帖子。
但我不确定如何将两个查询合并为一个。
SELECT *
FROM threads
ORDER BY title
SELECT comment, username
FROM posts
WHERE thread_id =...
ORDER BY post_datetime
DESC LIMIT 1
我试过:
SELECT t.title
FROM threads t
LEFT JOIN(
SELECT comment, username, thread_id
FROM posts
ORDER BY post_datetime DESC LIMIT 1
) d
ON t.thread_id = d.thread_id
ORDER BY t.title
但这只会返回论坛主题的标题(已排序)。
最佳答案
你应该阅读有关加入的内容:
SELECT t.title, p.comment, p.username, p.thread_id
FROM threads t
INNER JOIN posts p
ON t.thread_id = p.thread_id
ORDER BY t.title, p.post_datetime
关于mysql - 如何将 2 个 MySQL 查询合并为一个查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34726689/