繁体   English   中英

当日期来自2个字段时,MYSQL union如何维护日期字段顺序?

[英]MYSQL union how to maintain date field order when date came from 2 fields?

我有两个表TransactionsExpenses 我写了一个查询来获取日期明智的交易声明。 这里的交易表是存款表。 对于这个查询,我在没有订单日期的情况下得到了我想要的结果。

SELECT IFNULL(date(t1.created), date(ex.created)) as Date , sum(t1.amount) as ReceiveAmount,ex.amount as ExpensesAmount 
    FROM transactions as t1
    LEFT JOIN (
        SELECT sum(e.amount) as amount, created
           FROM expenses as e 
           group by date(e.created)
        ) as ex
    ON date(ex.created) =  date(t1.created)
    GROUP BY date(t1.created)

    UNION

    SELECT IFNULL(date(t1.created), date(ex.created)) as Date, sum(t1.amount) as Receive,ex.amount as ExpensesAmount 
    FROM transactions as t1

    RIGHT JOIN (
        SELECT sum(e.amount) as amount, created
        FROM expenses as e 
        group by date(e.created)
    ) as ex
    ON date(t1.created) = date(ex.created)
    GROUP BY date(t1.created)

输出 :

Date       ReceiveAmount    ExpensesAmount  
2018-12-04     600            NULL
2019-08-01     500            NULL
2019-10-18     500            NULL
2019-11-18     820            500  <== that should come at last.
2019-11-04     NULL           100

我需要查看日期 ASC 订单。 这里最后 2 个日期2019-11-182019-11-04没有维护订单。 我怎么解决这个问题 ?

在将联合的两半放在括号中之后,您可以在联合查询中添加ORDER BY子句:

(SELECT IFNULL(t1.created, DATE(ex.created)) AS Date, SUM(t1.amount) AS ReceiveAmount,
     ex.amount AS ExpensesAmount 
FROM transactions as t1
LEFT JOIN
...
)

UNION ALL

(SELECT IFNULL(t1.created, DATE(ex.created)), SUM(t1.amount), ex.amount
FROM transactions as t1
RIGHT JOIN
...
)
ORDER BY Date

我在这里假设你真的想要一个UNION ALL ,而不是一个UNION 请注意,在大多数其他 RDBMS 中,您必须使用正式子查询将ORDER BY子句应用于整个联合查询。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM