如果mysql中没有行/空结果,则返回0

时间:2014-04-01 17:18:20

标签: mysql

如果我在mysql中得到一个空结果,有没有办法可以返回0?

SELECT t1.amount as Amt
FROM table1 as t1
INNER JOIN table2 as t2
ON t1.project_id = t2.id

WHERE t2.proj_name = "Project_Kalinga"
AND t1.date_sent = (SELECT MAX(date_sent) FROM table WHERE project_id = "0123")

目前,对于项目名称“Project Kalinga”,我得到一个空的结果。

有没有办法从这个查询中即使我得到一个空结果,我只会得到0而不是? 那么输出就像

| Amt |
|  0  |

谢谢!

这是sqlfiddle

http://sqlfiddle.com/#!2/0c4c5/2

2 个答案:

答案 0 :(得分:4)

你可以

  • 创建一个零
  • 的“虚拟行”
  • 对主查询执行左连接。
  • 合并实际值和虚拟值

SELECT Coalesce(t1.amt, d.amount) AS amt 
FROM   (SELECT 0 as amount
        FROM   DUAL) AS d
       LEFT JOIN  
       (SELECT t1.amount AS Amt 
        FROM   table1 AS t1 
               INNER JOIN table2 AS t2 
                       ON t1.project_id = t2.id 
        WHERE  t2.proj_name = "project_kalinga" 
               AND t1.date_sent = (SELECT Max(date_sent) 
                                   FROM   table1 
                                   WHERE  project_id = "0123")) AS t1 
       ON 1 = 1

Demo

答案 1 :(得分:2)

试试这个:

SELECT IFNULL(t1.amount,0) as Amt
FROM table t1
LEFT OUTER JOIN table2 t2
ON t1.project_id = t2.id AND t2.proj_name = "Project_Kalinga"
WHERE t1.date_sent = (SELECT MAX(date_sent) FROM table WHERE project_id = "0123")