SQL select直到完全排序问题
我正在尝试编写一些使用联合从多个表中提取的 SQL,其中行上的日期不到一个小时。
但是,如果 SQL 查询的总行数加起来没有达到大约 20 行,那么它应该将 where 更改为小于两小时的日期,依此类推,直到检索到 20 行。
这可以仅用 SQL 来完成吗?我也有一种使用 PHP 实现它的方法,但更喜欢用 SQL 来完成这一切。
I am trying to write some SQL that pulls from several tables using unions, where the date on the rows is less than a hour.
But if the total rows from the SQL query doesn't add up to about 20 then it should change the where to the date being less than two hours and so forth until 20 rows retrieved.
Is this possible to do solely in SQL? I have a way of implementing it using PHP as well, but would prefer to have it all done in SQL.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
按日期描述排序时,您应该选择前 20 个。
因此无需计算范围。Sql
Server
其他数据库
you should select the first 20 when ordered by date desc ..
so no need calculate the ranges..
Sql Server
other DBs
这可能不适用于所有数据库服务器,但是您应该能够执行诸如
从子查询中选择之类的操作,但会稍微减慢速度,并且您必须避免子查询中的 WHERE 子句(或者至少,将它们设置得足够远,以便它们始终返回至少 20 行)以便正常工作。
可能有一些非常相似的东西可以与 MySQL 一起使用,因为它不支持
TOP xxx
。你应该可以在最后说LIMIT 20
,但我不确定MySQL是否会让你从这样的子查询中进行选择。我记得过去遇到过问题,但坦率地说,MySQL 在 v5.0 之前只是一个玩具。This probably won't work for all DB servers, but you should be able to do something like
Selecting from a subquery slows things down a bit, though, and you'd have to avoid the WHERE clauses in the subquery (or at least, set them far enough back that they'd always return at least 20 rows) in order for things to work.
There's probably something very similar that'll work with MySQL, as it doesn't do
TOP xxx
. You should be able to sayLIMIT 20
at the end instead, but i'm not sure whether MySQL will let you select from subqueries like that. I remember having problems with it in the past, but frankly, MySQL was a toy til v5.0.