这是我的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(),然后从我想要的总数中减去它,并将该数字用作第二个查询的限制。我不知道这是怎么做到的。
提前致谢!
答案 0 :(得分:2)
这是必需的查询 -
select *
from
((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)) t
limit 0,25
答案 1 :(得分:1)
另一个选择:
select * from
(
(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)
) uniond_tables_alias
limit 25
uniond_tables_alias
是uniond部分的别名,您可以选择任何名称。
答案 2 :(得分:1)
不需要嵌套查询,只需执行:
(select * from items
where items.created > curdate() - interval 2 week
order by items.created desc) # remove LIMIT here
UNION ALL
(select * from items
where items.created < curdate() - interval 2 week
order by items.popularity desc) # remove LIMIT here
LIMIT 25; # add LIMIT here
如果存在至少25,则返回第一个SELECT的25个第一个结果。否则,它将用第二个SELECT结果填充剩余的结果,直到达到25的限制。
答案 3 :(得分:0)
SELECT 1 AS sortkey, * from items ....
UNION ALL
SELECT 2 AS sortkey, * from items ....
ORDER BY sortkey, etc.
LIMIT 25