我有两个表交易和费用。我已经编写了一个查询来获取日期明智的交易语句。这里的交易表是存款表。对于这个查询,我得到了我想要的结果,没有订单日期。
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-18 和 2019-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/