我需要表T1和T2
T1
Id name open receive close
1 jon 5000 4000 1000
2 jim 6000 5000 1000
T2
Id name receive
1 jon 500
2 jim 700
我想要这样(T1接收+ T2接收)结果
Id name open receive close
1 jon 5000 4500 500
2 jim 6000 5700 300
我正在使用Sqlite
答案 0 :(得分:2)
更新:Tim Biegeleisen的回答更为正确。
你需要在这两个表上进行连接:
SELECT T1.id, T1.open, T1.receive+T2.receive, T1.close
FROM T1 JOIN T2 USING (id);
修改:如果您想要更新T1
,可以这样做:
UPDATE T1
SET receive=receive+coalesce((SELECT receive FROM T2 WHERE T1.id=T2.id),0);
答案 1 :(得分:2)
SELECT T1.name,
T1.open,
T1.receive + COALESCE(T2.receive, 0) AS receive,
T1.close - COALESCE(T2.receive, 0) AS close
FROM T1
LEFT JOIN T2
ON T1.Id = T2.Id
如果你想UPDATE
第一张表,你可以试试这个:
UPDATE T1
SET T1.recieve = T1.recieve +
(SELECT COALESCE(T2.recieve, 0) FROM T2 WHERE T2.Id = T1.Id),
T1.close = T1.close -
(SELECT COALESCE(T2.recieve, 0) FROM T2 WHERE T2.Id = T1.Id)
答案 2 :(得分:1)
如果每id
只有一行,则可以执行以下操作:
select t1.id, t1.name, t1.open, (t1.receive + t2.receive), t1.close
from t1 join
t2
on t1.id = t2.id;
我可以推测t2
实际上对于给定的id或缺少的行有多行。这表明:
select t1.id, t1.name, t1.open, (t1.receive + t2.receive), t1.close
from t1 left join
(select t2.id, sum(t2.receive) as receive
from t2
group by t2.id
) t2
on t1.id = t2.id;