SQL:使用 UNION、ORDER BY 和 LIMIT 进行 SELECT
我收到的错误是 ORDER by 应该在 UNION 之后出现,但我希望这些查询在合并为 1 之前排序,然后限制为 10。
SELECT *
FROM (SELECT time, x, y, z
FROM db
WHERE time >= now
ORDER by time, x
UNION
SELECT time, x, y, z
FROM db
WHERE time < now
ORDER by time, x)
LIMIT 10
我希望您理解我正在尝试做什么并且可以帮助我;-)
I'm getting Errors that ORDER by should come after UNION but i want these to queries ordered before combined to one and then limited to 10.
SELECT *
FROM (SELECT time, x, y, z
FROM db
WHERE time >= now
ORDER by time, x
UNION
SELECT time, x, y, z
FROM db
WHERE time < now
ORDER by time, x)
LIMIT 10
I hope you understand, what I'm trying to do and can help me ;-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果你在 SQLite 中有一个非常复杂的查询,但需要使用 UNION 进行排序,那么你可以尝试
if you have a very complex query in SQLite but need to use UNION with ordering, then you can try
订单将影响整个联盟。
无论如何,看起来您想要最接近
now
的行。你可以试试这个:An order by will affect the ENTIRE union.
Anyway, it looks like you want the rows nearest to
now
. You could try this:在“标准”(对于“标准”的某些定义)SQL;
如何限制结果集中的行数可能因 SQL 实现而异。
In "standard" (for some definition of "standard") SQL;
How to limit the number of rows in the result set may vary between SQL implementations.
这不是它的工作原理,至少在 MySQL 中(你没有指定)。 ORDER 操作是在选择数据并且执行了所有 UNION、GROUP BY 等之后进行的。
请参阅 SQL Server:在子查询中使用 UNION 进行 ORDER BY 了解绕过这个。
That's not how it works, at least in MySQL (you didn't specify). The ORDER operation comes after the data is selected and all UNIONs, GROUP BYs, etc. have been performed.
See SQL Server: ORDER BY in subquery with UNION for a way around this.
我应用的任何简单解决方案如下:
这按第二(日期)列对结果进行排序。
如果日期列是字符串,则可以应用上面所示的 TO_DATE 函数,否则没有必要。
Any easy solution I applied was as follows :
This orders the results by the second (date) column.
If the date column is a string, you can apply the TO_DATE function as shown above, else it is not necessary.