我希望从一个表中获取完整列,并从另一个具有相同id的表中选择sum。
例如:
table1 table2
id target id target achived
1 40 1 20
2 50 2 25
3 66
4 80
我希望从表1中选择所有内容并在其上填充已成功的目标结果。
例如:
id target target achived
1 40 20
2 50 25
3 66 0
4 80 0
how can i do that using mysql
答案 0 :(得分:1)
使用此查询:
select table1.*, case when table2.target_achieved is null
then 0
else table2.target_achieved
end as target_achieved
from table1 left join table2
on table1.id = table2.id
order by table1.id
答案 1 :(得分:0)
以下查询结果为0
而不是NULL
SELECT t1.id, target, COALESCE(target_achieved, 0) AS target_achieved
FROM table1 AS t1
LEFT JOIN table2 AS t2
ON t1.id = t2.id;