MySQL子查询返回空

时间:2018-11-15 02:58:12

标签: mysql

嗨,我是一个初学者,我正在尝试使子查询的所有结果行都为null,以返回0而不为null。但我遇到一个错误。我将非常感谢任何建议。谢谢

错误代码:1064 您的SQL语法有误;查看与您的MySQL服务器版本相对应的手册,以获取在'AS'Income'附近使用正确的语法

SELECT  

 COUNT(DISTINCT t1.id) AS 'Val1',


     COALESCE((SELECT SUM(CAST(COALESCE(r.t_payment_total,0) AS DECIMAL(18,2))) AS 'Income'
FROM reserv r
INNER JOIN newtbladds1 t ON t.t_parent_id = r.id
 WHERE r.t_status!="Pending" && r.t_status!="Booked" AND r.c_mid = m.id AND  t.t_type_id = t1.t_type_id 
 ),0)AS 'Income'



 FROM tbladds1 t1
JOIN tbladds1_type tt ON tt.id = t1.t_type_id
JOIN tbladdress m ON m.id = t1.t_mid
JOIN tbladdressfr mf ON mf.id = t1.t_floor_id
JOIN tblppl mp ON mp.t_mid = m.id AND mp.t_type = 'try' AND mp.t_system_id = 'ok'
GROUP BY t1.t_tool_type_id
ORDER BY m.t_m ASC, tt.t_ttype ASC, mf.t_floor ASC;

我删除了输出COALESCE,我的输出为空

Val1           Income
10              Null
2               30
23              10
5               Null

所需的输出

Val1           Income
10              0
2               30
23              10
5               0

1 个答案:

答案 0 :(得分:0)

我建议将子查询移至from子句

SELECT
    t1.t_tool_type_id
  , COUNT( DISTINCT t1.id ) AS `Val1`
  , COALESCE(i.Income , 0 ) AS `Income`
FROM tbladds1 t1
JOIN tbladds1_type tt ON tt.id = t1.t_type_id
JOIN tbladdress m ON m.id = t1.t_mid
JOIN tbladdressfr mf ON mf.id = t1.t_floor_id
JOIN tblppl mp ON mp.t_mid = m.id
    AND mp.t_type = 'try'
    AND mp.t_system_id = 'ok'
left join (
        SELECT
             CAST( SUM(r.t_payment_total) AS decimal(18, 2) ) AS `Income`
        FROM reserv r
        INNER JOIN newtbladds1 t ON t.t_parent_id = r.id
        WHERE r.t_status != 'Pending'
        AND r.t_status != 'Booked'
        AND r.c_mid = m.id
        GROUP BY
            t.t_type_id
    ) as i on t1.t_type_id = i.t_type_id
GROUP BY
    t1.t_tool_type_id
;

nb:我假设r.t_payment_total是数字。

我还建议您始终使用单引号表示值/文字,并在MySQL反引号中使用标识(例如列标题),但实际上在查询中它们并不是必需的。