SELECT unit.*, sum( detail.order_money ) order_amount, sum( detail.one_commission ) one_commission, sum( detail.two_commission ) two_commission, ( sum( detail.two_commission ) + sum( detail.one_commission ) ) AS total_commission FROM profit_dividend_unit unit LEFT JOIN profit_dividend_detail detail ON unit.dividend_code = detail.dividend_code 修改改条sql,需要左表全部数据,没有对应的右表字段则显示空
时间: 2024-02-28 07:56:14 浏览: 132
IEC60071.zip_ IEC60071_IEC_IEC 600*_Protection_iec60071
5星 · 资源好评率100%
可以使用 `LEFT OUTER JOIN`,同时使用 `COALESCE` 函数来将没有对应的右表字段显示为空。
修改后的 SQL 如下所示:
```
SELECT unit.*,
COALESCE(sum(detail.order_money), 0) as order_amount,
COALESCE(sum(detail.one_commission), 0) as one_commission,
COALESCE(sum(detail.two_commission), 0) as two_commission,
COALESCE((sum(detail.two_commission) + sum(detail.one_commission)), 0) as total_commission
FROM profit_dividend_unit unit
LEFT OUTER JOIN profit_dividend_detail detail ON unit.dividend_code = detail.dividend_code
GROUP BY unit.unit_id
```
在这个修改后的 SQL 中,我们使用了 `COALESCE` 函数,将可能为空的字段替换成了 0,确保了结果集中每一列都有值。同时,我们也保留了左表的全部数据,即使在右表中没有对应的记录。
阅读全文