mysql 与 order by 和 limit 合并

mysql union with order by and limit

有这样的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

但是,得到 id = 1,2,3,4,5...的结果(必须是 5,4,3,2,1) 为什么?请帮助我)

试试这样的东西:

(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

码型为

( SELECT ... ORDER BY ... LIMIT .. )
UNION ALL? DISTINCT? -- Which do you need?
( SELECT ... ORDER BY ... LIMIT .. )
ORDER BY ... LIMIT .. OFFSET ..;

是的,那是 ORDER BY ... 的 3 个副本。

在外面,你有 LIMIT n OFFSET m,但在里面使用 LIMIT m+n。

3 个副本的原因是为了最小化 tmp table 大小 -- 至少有 3 个 tmp tables。