SQLite 子查询可以包含 ORDER BY 吗?

Can SQLite subqueries contain ORDER BY?

我有以下 SQL 选择论坛主题以及有关 first/last 帖子、帖子数量和启动它的用户的附带信息:

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。我的做,他们工作。

它们是怎么工作的?我是不是很幸运,我应该以其他方式构建我的查询吗?

您正在生成的子查询类型在 SQL 中称为 标量子查询。这是一个 returns 一列最多一行的子查询。它计算单个值,可用于 selectwhere 子句,例如。

documentation for expressions 描述了标量子查询:

Subquery Expressions

. . .

A subquery that returns a single column is a scalar subquery and can be used most anywhere. A subquery that returns two or more columns is a row value subquery and can only be used as the operand of a comparison operator.

order by.

的使用没有区别

实际上,您的子查询类型实际上是一个标量相关子查询,但同样的推理也适用。

我应该注意到 SQLite 中表达式的语法图似乎缺少标量子查询。所以文档解释了它。我认为这是文档中的错误。

虽然您可以使用教程作为指导,但如果您真的想知道数据库的功能,请查看该数据库的文档。