订购UNION MySQL查询时出错

时间:2016-11-09 13:18:45

标签: mysql sql-order-by union

以下查询引发错误:#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'UNION (' at line 15

以下是查询:

(SELECT 'receivables'       AS entry_type, 
        rp.amount_recieved  AS amount, 
        rp.rp_id            AS payment_document_id, 
        rp.paidwith         AS payment_type, 
        rp.payment_doc_date AS payment_document_date, 
        r.id                AS document_id, 
        c.comp_name         AS company 
 FROM   receivables_payments rp, 
        receivables r, 
        comp_companies c 
 WHERE  rp.r_id = r.id 
        AND r.supplier = c.comp_id 
        AND r.beneficiary_id = '1' 
        AND rp.payment_doc_date BETWEEN '2016-10-01' AND '2016-11-09') 
UNION 
(SELECT 'payables'          AS entry_type, 
        pp.amount_recieved  AS amount, 
        pp.pp_id            AS payment_document_id, 
        pp.paidwith         AS payment_type, 
        pp.payment_doc_date AS payment_document_date, 
        p.id                AS document_id, 
        c.comp_name         AS company 
 FROM   payables_payments pp, 
        payables p, 
        comp_companies c 
 WHERE  pp.p_id = p.id 
        AND p.supplier = c.comp_id 
        AND p.beneficiary_id = '1' 
        AND pp.payment_doc_date BETWEEN '2016-10-01' AND '2016-11-09') 
ORDER  BY payment_document_date DESC 

可以请有人告诉我它有什么问题吗?因为我没有看到它。

谢谢。

1 个答案:

答案 0 :(得分:1)

尝试在外部查询中进行排序

SELECT * FROM (
(SELECT 'receivables'       AS entry_type, 
        rp.amount_recieved  AS amount, 
        rp.rp_id            AS payment_document_id, 
        rp.paidwith         AS payment_type, 
        rp.payment_doc_date AS payment_document_date, 
        r.id                AS document_id, 
        c.comp_name         AS company 
 FROM   receivables_payments rp, 
        receivables r, 
        comp_companies c 
 WHERE  rp.r_id = r.id 
        AND r.supplier = c.comp_id 
        AND r.beneficiary_id = '1' 
        AND rp.payment_doc_date BETWEEN '2016-10-01' AND '2016-11-09') 
UNION 
(SELECT 'payables'          AS entry_type, 
        pp.amount_recieved  AS amount, 
        pp.pp_id            AS payment_document_id, 
        pp.paidwith         AS payment_type, 
        pp.payment_doc_date AS payment_document_date, 
        p.id                AS document_id, 
        c.comp_name         AS company 
 FROM   payables_payments pp, 
        payables p, 
        comp_companies c 
 WHERE  pp.p_id = p.id 
        AND p.supplier = c.comp_id 
        AND p.beneficiary_id = '1' 
        AND pp.payment_doc_date BETWEEN '2016-10-01' AND '2016-11-09')) t1
ORDER  BY payment_document_date DESC;

希望这可以解决你的问题。