如何使用mysql更新同一个表中的值?

时间:2013-08-12 11:09:51

标签: mysql sql

我需要根据每个customer_id的att_id替换/更新表中的值。 该表看起来像:

ID att_id customer_id value
1  5            1     name
2  30           1     12345
3  40           1      
4  5            2     name2
5  30           2     12345
6  40           2     

我想像这样替换它:

ID att_id customer_id value
1  5            1     name
2  30           1     
3  40           1     12345 
4  5            2     name2
5  30           2     
6  40           2     12345

4 个答案:

答案 0 :(得分:3)

更新:根据您的评论 ...我需要查找属性30的值,检查它们是否为手机号码,如果是真的,请将其写入属性值40 ... 您的查询可能如下所示

UPDATE table1 t1 JOIN table1 t2
    ON t1.customer_id = t2.customer_id
   AND t1.att_id = 40 
   AND t2.att_id = 30
   SET t1.value = t2.value
  --  ,t2.value = NULL -- uncomment if you need to clear values in att_id = 30 at the same time
 WHERE t2.value REGEXP '^[+]?[0-9]+$'

您可能需要调整正则表达式以正确匹配您的记录(“手机号码”)

这是 SQLFiddle 演示


很难从您的说明中确切地说出来,但如果您需要按照customer_id交换att_id 3040的值,您可以执行以下操作

UPDATE table1 t1 JOIN table1 t2
    ON t1.customer_id = t2.customer_id
   AND t1.att_id = 40 
   AND t2.att_id = 30
   SET t1.value = t2.value,
       t2.value = t1.value

这是 SQLFiddle 演示

或者如果您需要将att_id = 30的值设置为att_id = 40并将att_id = 30的值设置为“{1}}

UPDATE table1 t1 JOIN table1 t2
    ON t1.customer_id = t2.customer_id
   AND t1.att_id = 40 
   AND t2.att_id = 30
   SET t1.value = t2.value,
       t2.value = NULL 

这是 SQLFiddle 演示

答案 1 :(得分:1)

以下是将att_id等于30和40的行交换为值的一般方法:

update t join
       t t30
       on t.customer_Id = t30.customer_Id and t30.att_id = 30 join
       t t40
       on t.customer_Id = t40.customer_Id and t40.att_id = 40 join
    set t.value = (case when att_id = 30 then t40.value 
                        when att_id = 40 then t30.value 
                        else t.value
                   end)
    where att_id in (30, 40);

答案 2 :(得分:0)

首先,删除att_id = 30

的值

UPDATE tablename SET value="" WHERE att_id=30;

然后设置att_id = 40

的值

UPDATE tablename SET value="12345" WHERE att_id=40;

答案 3 :(得分:0)

UPDATE tableName SET value=12345 WHERE ID=2;
UPDATE tableName SET value="" WHERE ID=3;
UPDATE tableName SET value=12345 WHERE ID=6;
UPDATE tableName SET value="" WHERE ID=5;

这是命令。有关更新的教程,请参阅http://www.tutorialspoint.com/mysql/mysql-update-query.htm