MySQL UNION ALL 排序失效问题

    具体场景:有两张表,因业务需要需要汇总查询数据,A表需要按照创建时间倒序排列,B表需要根据设置好的排序号进行排序,

同时A表数据排在B表数据之前,单表查找是没有问题的,union all 之后排序就全乱了,找了找资料发现对每个子查询添加“limit”限制之后就可以了,具体SQL语句如下

        SELECT
        *
        FROM
        (
            (
            SELECT
	    *
            FROM
            import a
            WHERE a.organization_id = 1
            AND a.del_flag = 0
            AND subString(a.create_time, 1, 4) = 2020
            ORDER BY a.create_time DESC
            LIMIT 999999
            )
        UNION ALL
            (
            SELECT
	    *
            FROM
            report r
            LEFT JOIN organization o
            ON r.organization_id = o.id
            WHERE r.organization_id in (143,177,191)
            AND r.report_status = 1
            AND subString(r.create_time, 1, 4) = 2020
            ORDER BY o.serial_number ASC
            LIMIT 999999
            )
        )tmp
        LIMIT 0, 10

 

你可能感兴趣的:(工作中的"疑难杂症")