donglang6656 2015-09-14 17:50
浏览 148
已采纳

Mysql IFNULL只在多个SELECT查询中工作一次

I'm trying to build a month graphic using a MySQL query. I'm checking how many rows there are in a table for each month in a single query using the UNION command. Example with 3 months bellow:

$query =
"SELECT IFNULL((SELECT SUM(score) FROM statistics WHERE MONTH(date) = 1), 0) AS total UNION
 SELECT IFNULL((SELECT SUM(score) FROM statistics WHERE MONTH(date) = 2), 0) AS total UNION
 SELECT IFNULL((SELECT SUM(score) FROM statistics WHERE MONTH(date) = 3), 0) AS total";

$stats_query = mysqli_query ($db_connection, $query);

  $result = "";
  while ($row = mysqli_fetch_assoc($stats_query)) {
    $result .= $row['total'].",";
  }
  echo ($result);

// OUTPUT: 0,176,68,

As you can see, I'm telling mysql to return me a "0" in case there are no rows for that month (which is the case for January).

There are a total of 12 SELECTS in that query (I copied just 3 to save space), one for each month. Some months will return a value, others won't (which the IFNULL should then convert to a "0"). My final output, for all the 12 months, should look like this:

// OUTPUT: 0,176,68,0,0,0,0,0,12,15,176,43,

BUT... if there is more than one SELECT that returns no rows, the query won't add another "0" to the result. My final result ends up being like this:

// OUTPUT: 0,176,68,12,15,176,43,

It's like the IFNULL is only executed once, even though he's present in all the 12 SELECTS...

Am I doing something wrong? Can anyone spot an error in my code or something?

Thank you!

  • 写回答

1条回答 默认 最新

  • doulangbi6869 2015-09-14 17:52
    关注

    Use UNION ALL instead of UNION to get all results:

     SELECT IFNULL((SELECT SUM(score) FROM statistics WHERE MONTH(date) = 1), 0) AS total UNION ALL
     SELECT IFNULL((SELECT SUM(score) FROM statistics WHERE MONTH(date) = 2), 0) AS total UNION ALL
     SELECT IFNULL((SELECT SUM(score) FROM statistics WHERE MONTH(date) = 3), 0) AS total
    

    UNION returns only DISTINCT rows.

    From doc:

    The default behavior for UNION is that duplicate rows are removed from the result.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 准备学习小程序搭建,谁能手把手的教我啊?
  • ¥15 关于#嵌入式硬件#的问题:树莓派第一天重装配置python和opencv后第二天打开就成这样,瞎捣鼓搞出来文件夹还是没把原来的界面调回来
  • ¥20 Arduino 循迹小车程序电路出错故障求解
  • ¥20 Arduino 循迹小车程序电路出错故障求解
  • ¥100 AT89C52单片机C语言调试之后再回答
  • ¥15 AT89C52单片机C语言串口助手发送数据包返回值
  • ¥15 C++数组中找第二小的数字程序纠错
  • ¥15 wannier复现图像时berry曲率极值点与高对称点严重偏移
  • ¥15 利用决策森林为什么会出现这样·的问题(关键词-情感分析)
  • ¥15 DispatcherServlet.noHandlerFound No mapping found for HTTP request with URI[/untitled30_war_e