[英]mysql union with order by and limit
a have such sql: 有这样的sql:
(select `ads`.*
from `ads`
where `status` = ?
and `lat` between ? and ?
and `lng` between ? and ?
and NOW() between ads.featured_start and ads.featured_end
order by `ads`.`id` desc)
union
(select `ads`.*
from `ads`
where `status` = ?
and `lat` between ? and ?
and `lng` between ? and ?
and NOW() not between ads.featured_start and ads.featured_end
order by `ads`.`id` desc)
limit 8 offset 0
but, get results with id = 1,2,3,4,5... (it is necessary 5,4,3,2,1) why? 但是,获得id = 1,2,3,4,5的结果......(这是必要的5,4,3,2,1)为什么? help me please) 请帮帮我)
Try something like: 尝试类似的东西:
(select `ads`.*
from `ads`
where `status` = ?
and `lat` between ? and ?
and `lng` between ? and ?
and NOW() between ads.featured_start and ads.featured_end
union
select `ads`.*
from `ads`
where `status` = ?
and `lat` between ? and ?
and `lng` between ? and ?
and NOW() not between ads.featured_start and ads.featured_end)
ORDER BY id DESC
limit 8 offset 0
The code pattern is 代码模式是
( SELECT ... ORDER BY ... LIMIT .. )
UNION ALL? DISTINCT? -- Which do you need?
( SELECT ... ORDER BY ... LIMIT .. )
ORDER BY ... LIMIT .. OFFSET ..;
Yes that is 3 copies of ORDER BY ...
. 是的,这是3份ORDER BY ...
Outside, you have LIMIT n OFFSET m, but inside use LIMIT m+n. 外面,你有LIMIT n OFFSET m,但内部使用LIMIT m + n。
The reason for the 3 copies is to minimize the tmp table sizes -- there will be at least 3 tmp tables. 3个副本的原因是最小化tmp表大小 - 至少有3个tmp表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.