子查询中的ORDER BY是否会使外部查询记录按相同顺序排序?
子查询中的ORDER BY是否会影响外部查询的排序?
答案很明确:不会,子查询里的ORDER BY并不会让外部查询的结果自动遵循相同的排序规则。
为什么会这样?
你用的是IN子查询,这类子查询的作用是返回一个值的集合,而数据库里的「集合」是没有固定顺序的——优化器通常会直接忽略IN子查询里的ORDER BY(除非子查询搭配了LIMIT这类限制返回行数的语句,你的例子里并没有)。外部查询的结果顺序,完全由它自身是否显式声明了ORDER BY决定:
- 如果外部查询没写
ORDER BY,数据库会返回任意顺序的结果(可能偶尔和子查询顺序巧合一致,但这是不可靠的,依赖于数据库的执行计划、数据存储方式等,不能作为业务逻辑的依据); - 只有在外部查询末尾加上自己的
ORDER BY子句,才能保证结果的排序符合预期。
结合你的示例SQL说明
看你给出的这段SQL:
select p.email email, max(p.firstname) firstname,max(p.lastname) lastname from abc p, xyz c where p.companyid=c.companyid and c.company!='' and locationid in ( select locationid from mno tr where 1=1 AND tr.inc in (7,8,9) AND tr.topic in( 'Callidus Cloud') AND tr.inc IS NOT NULL order by inc desc ) AND c.crange IN ...
这里子查询里的order by inc desc对外部查询的结果排序没有任何影响。如果你想让外部查询的结果按inc或者其他字段排序,需要把inc字段关联到外部查询中(比如通过JOIN),然后在外部查询的最后加上ORDER BY,比如:
select p.email email, max(p.firstname) firstname,max(p.lastname) lastname, max(tr.inc) inc from abc p, xyz c, mno tr where p.companyid=c.companyid and c.company!='' and p.locationid = tr.locationid AND tr.inc in (7,8,9) AND tr.topic in( 'Callidus Cloud') AND tr.inc IS NOT NULL AND c.crange IN ... group by p.email order by inc desc
补充说明
只有当子查询作为FROM子句的数据源(也就是把子查询当作一张临时表)时,里面的ORDER BY搭配LIMIT才有意义——比如你想取子查询的前N行数据。但对于IN、EXISTS这类子查询,ORDER BY基本是无效的,因为这类子查询只关心「值是否存在」,不关心值的顺序。
内容的提问来源于stack exchange,提问作者clint
相关产品推荐
相关产品推荐

