【问题标题】:Set default value if no result found如果未找到结果,则设置默认值
【发布时间】:2016-09-01 04:14:48
【问题描述】:

我有以下查询

SELECT count(*) as count, Month(created_at) as month 
FROM products 
WHERE marketplace_id=21
      and status='counterfeit' 
      and created_at < Now() 
      and created_at > DATE_ADD(Now(), INTERVAL - 5 MONTH)
group by month(created_at)

返回结果为

+-------+-------+
| count | month |
+-------+-------+
|   410 |     1 |
|   174 |     2 |
|   301 |     3 |
|   329 |     4 |
|   141 |    12 |
+-------+-------+

如果一个月没有值,它根本不会返回它,但我希望为该月设置默认值 0。

我试过this link Return a default value if no rows found

Returning a value if no result

我不确定是我无法正确实现还是这不是我想要的

【问题讨论】:

  • 可能会创建一个日历表并仅存储月份(12 行)并对该表进行左连接。

标签: mysql sql


【解决方案1】:

试试这个,好像有点傻,不过可能对你有帮助;)

SELECT SUM(count) AS count, month
FROM (
    SELECT count(*) as count, Month(created_at) as month FROM products WHERE marketplace_id=21
            and status='counterfeit' and created_at < Now() and created_at > DATE_ADD(Now(), INTERVAL - 5 MONTH)
            group by month(created_at)
    UNION 
    SELECT * FROM (
        SELECT 0 AS count, 1 AS month
        UNION SELECT 0 AS count, 2 AS month
        UNION SELECT 0 AS count, 3 AS month
        UNION SELECT 0 AS count, 4 AS month
        UNION SELECT 0 AS count, 5 AS month
        UNION SELECT 0 AS count, 6 AS month
        UNION SELECT 0 AS count, 7 AS month
        UNION SELECT 0 AS count, 8 AS month
        UNION SELECT 0 AS count, 9 AS month
        UNION SELECT 0 AS count, 10 AS month
        UNION SELECT 0 AS count, 11 AS month
        UNION SELECT 0 AS count, 12 AS month) M
    WHERE M.month < Month(Now()) AND M.month > Month(DATE_ADD(Now(), INTERVAL - 5 MONTH)))
) tmp
GROUP BY mouth
ORDER BY month

【讨论】:

  • 好吧,这行得通,但这里的问题是它为全年提供价值,如果我从 8 月开始并想要过去 6 个月的 8 月、7 月、6 月、5 月、4 月和 3 月的数据怎么办
  • 类似where month &gt;= Month(created_at)
  • 嗯,你们说的很对,我已经更新了帖子,请再看一遍。
【解决方案2】:

您可以使用默认值创建另一个表

  test_defaults
-----------------
| month | count |

而不仅仅是left join 它与您的值表,所以如果在主表中找到该值,它将被使用,如果不是来自 test_defaults 的值将被使用(我们将使用 COALESCE 函数,它首先返回非空值):

SELECT t1.month, COALESCE(t2.count, t1.count)
FROM test_defaults t1
LEFT JOIN test_data t2 ON t1.month = t2.month
ORDER BY t1.month;

Here's a working SqlFiddle demo

【讨论】:

    猜你喜欢
    • 2019-04-12
    • 1970-01-01
    • 2015-12-02
    • 1970-01-01
    • 2020-03-19
    • 2013-02-25
    • 2010-11-22
    相关资源
    最近更新 更多