MySQL 联合排序 select 语句分开而不是合并

MySQL union sorting select statements separately instead of combining

我的查询有效并且给出了正确的结果 -- 但它分别对两个选择结果集进行排序,然后将第二个结果集连接到第一个结果集的末尾,我不知道为什么!我希望两套一起订购。

(SELECT 
    m.m_name AS 'Merchant',
    log.ship_day AS 'Date',
    log.num_orders AS '# Orders',
    'Sales Exec' AS 'Dept',
    CONCAT(ciii.i_fname, ' ', ciii.i_lname) AS 'Rep',
    log.m_sales_executive_days AS 'Days',
    CONCAT(log.m_sales_executive_level,
            ' (',
            log.m_sales_executive_com,
            '*',
            log.num_orders,
            ')') AS 'Level',
    log.m_sales_executive_payout AS 'Payout'
FROM
    commissions.commissions_log AS log
        LEFT JOIN
    acf_rds_new.merchants m ON m.m_id = log.m_id
        LEFT JOIN
    acf_rds_new.users uuu ON uuu.u_id = log.m_sales_executive
        LEFT JOIN
    acf_rds_new.contact_info ciii ON uuu.u_i_id = ciii.i_id
        LEFT JOIN
    acf_rds_new.users uuuu ON uuuu.u_id = log.m_account_manager
        LEFT JOIN
    acf_rds_new.contact_info ciiii ON uuuu.u_i_id = ciiii.i_id) 

UNION ALL 

(SELECT 
    m.m_name AS 'Merchant',
    log.ship_day AS 'Date',
    log.num_orders AS '# Orders',
    'Account Exec' AS 'Dept',
    CONCAT(ciiii.i_fname, ' ', ciiii.i_lname) AS 'Rep',
    log.m_account_manager_days AS 'Days',
    CONCAT(log.m_account_manager_level,
            ' (',
            log.m_account_manager_com,
            '*',
            log.num_orders,
            ')') AS 'Level',
    log.m_account_manager_payout AS 'Payout'
FROM
    commissions.commissions_log AS log
        LEFT JOIN
    acf_rds_new.merchants m ON m.m_id = log.m_id
        LEFT JOIN
    acf_rds_new.users uuu ON uuu.u_id = log.m_sales_executive
        LEFT JOIN
    acf_rds_new.contact_info ciii ON uuu.u_i_id = ciii.i_id
        LEFT JOIN
    acf_rds_new.users uuuu ON uuuu.u_id = log.m_account_manager
        LEFT JOIN
    acf_rds_new.contact_info ciiii ON uuuu.u_i_id = ciiii.i_id) 

ORDER BY 'Date' ASC , 'Merchant' ASC , '# Orders' DESC

如果您想要 ordered 整个结果集,您应该有另一个 select 语句。

select * from
(your query with union all) t
order by 'Date' ASC , 'Merchant' ASC , '# Orders' DESC

如果您希望对两个子查询进行排序,那么请不要在您的 order by 语句中使用常量。正确的转义字符是反引号,但你只需要最后一列:

ORDER BY Date ASC , Merchant ASC , `# Orders` DESC

一般来说,不要对列名使用单引号。 对字符串和日期常量使用单引号。否则,您很容易出错,例如您查询中的错误。

根据the docs

To use an ORDER BY or LIMIT clause to sort or limit the entire UNION result, parenthesize the individual SELECT statements and place the ORDER BY or LIMIT after the last one. The following example uses both clauses:

(SELECT a FROM t1 WHERE a=10 AND B=1)
UNION
(SELECT a FROM t2 WHERE a=11 AND B=2)
ORDER BY a LIMIT 10;