我有以下 SQL 选择讨论论坛线程,并附带有关第一个/最后一个帖子、帖子数量和启动它的用户的信息:
SELECT forum_threads.*,
users.displayname as cc_username,
coalesce(count(forum_posts.id),0) AS cc_postCount,
(select id from forum_posts where threadId=forum_threads.id order by tsCreate asc limit 1) as cc_firstPostId,
(select id from forum_posts where threadId=forum_threads.id order by tsCreate desc limit 1) as cc_lastPostId,
(select tsCreate from forum_posts where threadId=forum_threads.id order by tsCreate desc limit 1) as cc_tsLatest
FROM forum_threads
LEFT JOIN forum_posts ON forum_posts.threadId = forum_threads.id
LEFT JOIN users ON users.id = forum_threads.userId
GROUP BY forum_threads.id
ORDER BY forum_posts.tsCreate DESC
它似乎工作正常,但我刚刚在Tutorialspoint上读到SQLite 子查询不能包含ORDER BY
. 我的做,他们工作。
他们是怎么工作的?我只是幸运吗,我应该以其他方式构造我的查询吗?