SQL select直到完全排序问题

发布于 2024-09-11 22:48:24 字数 188 浏览 3 评论 0原文

我正在尝试编写一些使用联合从多个表中提取的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

地狱即天堂 2024-09-18 22:48:24

按日期描述排序时,您应该选择前 20 个。

因此无需计算范围。Sql

Server

SELECT TOP 20 ..

其他数据库

SELECT ... LIMIT 0, 20

you should select the first 20 when ordered by date desc ..

so no need calculate the ranges..

Sql Server

SELECT TOP 20 ..

other DBs

SELECT ... LIMIT 0, 20
慵挽 2024-09-18 22:48:24

这可能不适用于所有数据库服务器,但是您应该能够执行诸如

SELECT TOP 20 * 
FROM (SELECT your columns from table1 UNION SELECT your columns from table2) temp
ORDER BY [the date column] DESC

从子查询中选择之类的操作,但会稍微减慢速度,并且您必须避免子查询中的 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

SELECT TOP 20 * 
FROM (SELECT your columns from table1 UNION SELECT your columns from table2) temp
ORDER BY [the date column] DESC

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 say LIMIT 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文