Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
具有order by和limit的mysql并集_Mysql_Sql_Sql Order By - Fatal编程技术网

具有order by和limit的mysql并集

具有order by和limit的mysql并集,mysql,sql,sql-order-by,Mysql,Sql,Sql Order By,a有这样的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` wh

a有这样的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 ..;
是的,这是……订购的3份

在外部,您有限制n偏移量m,但在内部使用限制m+n

使用3个副本的原因是为了最小化tmp表的大小-至少有3个tmp表