MySQL 批量修改某一列的值为另外一个字段的值
MySQL 批量修改某一列的值为另外一个字段的值
| 1 2 3 4 5 6 7 8 9 10 11 | mysql> select* fromfruit;+----+--------+-------+| id | name| price |+----+--------+-------+|  1 | apple  |     0 ||  2 | banana |     0 ||  3 | orange |     0 ||  4 | mango  |     0 ||  5 | pomelo |     0 |+----+--------+-------+5 rowsinset(0.00 sec) | 
要求很简单,将上面fruit表的price列的值改为id列的值,比如第一条记录的price改成1(对应id)。
刚开始,我很天真的这样想:
1、用php或者其他的将所有记录都取出来
2、然后每一条记录,单独修改一次
这样就存在一个问题,效率并不高,首先,发请求、等待数据库执行,然后在迭代下一条记录。
然后换了一种方法,就是下面这个语句:
| 1 | mysql> updatefruit a setprice = (selectid fromfruit b wherea.id = b.id); | 
其实SQL语句写的特别明白,意思也没问题,但是,mysql不支持更改一种表,这种表就是在from子句中的表。
所以,上面报错信息如下:
ERROR 1093 (HY000): You can't specify target table 'a' for update in FROM clause
公布答案:
直接更新price=id
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | mysql> updatefruit setprice=id;Query OK, 5 rowsaffected (0.00 sec)Rowsmatched: 5  Changed: 5  Warnings: 0mysql> select* fromfruit;+----+--------+-------+| id | name| price |+----+--------+-------+|  1 | apple  |     1 ||  2 | banana |     2 ||  3 | orange |     3 ||  4 | mango  |     4 ||  5 | pomelo |     5 |+----+--------+-------+5 rowsinset(0.00 sec) | 
首先,我们在平常的update、insert、where筛选中,如果值的类型是字符串型,那么我们通常会使用引号将其括起来,但是我们并没有将字段名括起来。
在上面这一条命令中,set price=id,其实id也是字段名,并不是id的值。更新的时候,会自动取出其中的值来进行更新。
 
                    
                
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号