计算单个语句中第二个查询中第一个查询的 SQL 结果
这是我的 SQL 语句:
(select * from items
where items.created > curdate() - interval 2 week
order by items.created desc limit 0,10000000000)
union all
(select * from items
where items.created < curdate() - interval 2 week
order by items.popularity desc limit 0,15)
我正在尝试找出一种方法将查询的整个结果限制为某个数字(比如 25)。现在,这个结果为第一个结果返回无限数量(这就是我想要的),然后为第二个结果返回 15。我希望能够限制整个查询,这样即使第一个结果返回 8,第二个结果返回 17,总共 25。
我相信要做到这一点,我必须在第一个查询中以某种方式使用 count(),然后减去从我想要的总数中取出该数字,并将该数字用作第二个查询的限制。我不知道这是怎么做到的。
提前致谢!
Here's my SQL statement:
(select * from items
where items.created > curdate() - interval 2 week
order by items.created desc limit 0,10000000000)
union all
(select * from items
where items.created < curdate() - interval 2 week
order by items.popularity desc limit 0,15)
I'm trying to figure out a way to limit the entire result of the query to a certain number (say 25). As it is now, this result returns an unlimited number for the first result (which is what I want), then returns 15 for the second result. I want to be able to limit the whole query so that even if the first result returns 8, the second result returns 17, total 25.
I believe to do this, I have to use count() somehow in the first query, then subtract that from the total I want and use that number as the 2nd query's limit. I have no idea how this is done.
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是所需的查询 -
Here is the required query -
另一个选择:
uniond_tables_alias
是uniond部分的别名,您可以选择任何您想要的名称。Another select:
The
uniond_tables_alias
is an alias for the uniond section, you can choose any name you want.不需要嵌套查询,只需执行以下操作:
如果至少有 25 个,则将返回第一个 SELECT 的前 25 个结果。否则,它将用第二个 SELECT 结果填充剩余结果,直到达到 25 的限制。
No need for nested queries, simply do:
This'll return the 25 first results from the first SELECT if there's at least 25. Otherwise it will fill up the remaining results with the second SELECT results until the limit of 25 is reached.