如果未找到结果,请设置默认值

时间:2016-05-06 07:14:00

标签: mysql sql

我有以下查询

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

我不确定我是否无法正确实现它或者这不是我想要的

2 个答案:

答案 0 :(得分:2)

试试这个,似乎有点愚蠢,但可能对你有帮助;)

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

答案 1 :(得分:1)

您可以使用默认值

创建另一个表
  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

相关问题