Hi I have one tables here:
equipment
ID, Owner, Type, Count
1 Bob phone 10
2 Larry computer 11
1 Bob computer 11
What I am trying to do is add the computers that Bob, with id 1, to the computers of Larry's, with id 2. I'm trying to increase the count. The count should be 11+11=22. The new computer count for id 2 should be 22 and should update like this in the database:
equipment
ID, Owner, Type, Count
1 Bob phone 10
2 Larry computer 22
1 Bob computer 11
If Bob did not have any computer, meaning there was no record with ID = 2, then the record should be created.
Here is my 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;
Why are you using insert
to update a row?
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;
Some thing like this
UPDATE Yourtable a
JOIN Yourtable b
ON a.NAME = b.NAME
AND a.ID = b.ID + 1
SET a.Count = a.Count + b.Count
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.