嗨我这里有一张桌子:
equipment
ID, Owner, Type, Count
1 Bob phone 10
2 Larry computer 11
1 Bob computer 11
我要做的是将具有id 1的Bob的计算机添加到Larry的计算机中,ID为2.我正在尝试增加计数。计数应为11 + 11 = 22。 id 2的新计算机计数应为22,并且应该在数据库中更新如下:
equipment
ID, Owner, Type, Count
1 Bob phone 10
2 Larry computer 22
1 Bob computer 11
如果Bob没有任何计算机,意味着没有ID = 2的记录,那么应该创建记录。
这是我的SQL:
INSERT INTO EQUIPMENT(`ID`, `OWNER`, `TYPE`, `COUNT`)
SELECT 1 as t.ID, t.OWNER, t.TYPE, t.COUNT
FROM EQUIPMENT t
WHERE t.ID = 2
on duplicate key
update
COUNT = COUNT + t.COUNT;
答案 0 :(得分:0)
为什么使用insert
更新行?
update equipment e cross join
(select e1.* from equipment e1 where e1.id = 1) as e1
select e.count = e.count + e1.count
where e.id = 2;
答案 1 :(得分:0)
有点像这样
UPDATE Yourtable a
JOIN Yourtable b
ON a.NAME = b.NAME
AND a.ID = b.ID + 1
SET a.Count = a.Count + b.Count