简体   繁体   English

如何将同一表中的两个值相加并存储在同一表中的计算记录中?

[英]How do you add two values from the same table and store in calculated record in the same table?

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. 我想做的是将ID为1的Bob的计算机添加到ID为2的Larry's的计算机中。我试图增加计数。 The count should be 11+11=22. 计数应为11 + 11 = 22。 The new computer count for id 2 should be 22 and should update like this in the database: ID 2的新计算机数应为22,并应在数据库中按以下方式更新:

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. 如果Bob没有任何计算机,这意味着没有ID = 2的记录,则应创建该记录。

Here is my SQL: 这是我的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? 为什么使用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;

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM