MySQL select from subquery order

笑着哭i 提交于 2019-12-13 03:00:43

问题


If I have following table:

CREATE TABLE `docs` ( 
    `id` int(6) unsigned NOT NULL, 
    `rev` int(3) unsigned NOT NULL, 
    `content` varchar(200) NOT NULL, 
--
    PRIMARY KEY (`id`) 
) 

and execute following query:

select * 
from ( 
    select * 
    from docs 
    order by rev desc 
) as `rows`

will the order of returned rows be the same as order of inner query?

Can this be guaranteed, generally speaking?


回答1:


yes, If you are only using

select * 
from ( 
    select * 
    from docs 
    order by rev desc 
) as `rows`

then it will be same as always But using ORDER BY in subquery should not be done. Subquery used in some outer query, and that outer query will have to do ordering anyway, so there's no point ordering the subquery

if you use TOP or LIMIT in the subquery, you will need to use ORDER in Subquery. But that's not standard SQL

You should use it this way

SELECT * 
FROM ( 
    SELECT * 
    FROM docs 
) AS `rows` ORDER BY rev DESC;


来源:https://stackoverflow.com/questions/26301877/mysql-select-from-subquery-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!