[mysql]union中各自order by的问题

    技术2022-05-19  18

    对于union的简单介绍可以参考这里 。 如果你需要对各自的结果集先进行排序,然后在union起来的话: 一 首先举出错误的做法(代码为php) $sql1 = “select * from table where num>100 order by timestamp desc”; $sql2 = “select * from table where num<=100 order by timestamp asc”;

    如果将 $sql1 union $sql2 来执行的话,最后结果一般是乱序。无规律可循。

    二 正确做法:

    $sql1 = “select * from table where num>100 order by timestamp desc”; $sql2 = “select * from table where num<=100 order by timestamp asc”; $SQL= “select * from ($sql1) as temp1 union select * from ($sql2) as temp2″;


    最新回复(0)