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

标签 mysql

我有两个表交易费用。我已经编写了一个查询来获取日期明智的交易语句。这里的交易表是存款表。对于这个查询,我得到了我想要的结果,没有订单日期。

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 子句应用于整个联合查询。

关于当日期来自2个字段时,MYSQL union如何维护日期字段顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59127272/

相关文章:

php用redis实现一个队列

php - MySQL 表日期更新给出 00/00/0000 12 :00:00 am format in table

mysql - 用于记录回收的 SQL 触发器

Mysql SELECT 优先级

java.lang.IllegalArgumentException : Not a managed type - Multiple Databases in Spring Boot

php - 如何获取组之间的第一条和最后一条记录?

php - MySQL Delete Row 在需要时不删除多对多表中的值

php - sql查询不拉取记录

mysql - 在 mysql if 语句中使用来自另一个表的列

php - mysql_num_rows() 在使用 AND 时返回 0