我有一个这样的MySQL查询:

SELECT DAYNAME(CreatedAt) AS TheDay, SUM(Amount) AS TheSum
FROM OrderTransactions
GROUP BY TheDay

# Returns an array like:
# Array
# (
#     [0] => Array
#         (
#             [TheDay] => Thursday
#             [TheSum] => 0.02
#         )
#
#     [1] => Array
#         (
#             [TheDay] => Wednesday
#             [TheSum] => 0.02
#         )
#
# )


我那里还有一个子句,只选择上周的交易。如果在某些天没有交易,我如何仍能使它在每个空白天都返回0.00美元的金额?

最佳答案

通常,此处的技术是UNION,与您选择的相反。

假设您在表name中有一个表日名,其值为'Monday','Tuesday'...'Sunday'。

SELECT DAYNAME(CreatedAt) AS TheDay, SUM(Amount) AS TheSum
  FROM OrderTransactions
  GROUP BY TheDay
UNION
SELECT `name`, 0 FROM daynames
  WHERE daynames.name NOT IN (SELECT DISTINCT DAYNAME(CreatedAt) FROM OrderTransactions)


当您没有日期功能时,通常不需要日名查询表。在这种情况下,我不知道避免这种情况的捷径。

关于php - 按日期分组时如何使MySQL返回空日?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1647003/

10-10 23:40