简体   繁体   English

Mysql:根据另一列值更新列

[英]Mysql: Updating column based on another columns value

I have about 300 records in my database that have invalid data in a column.我的数据库中有大约 300 条记录,其中列中有无效数据。 The columns that are invalid reference a user_id instead of a id code (shown in table).无效的列引用 user_id 而不是 id 代码(如表所示)。

I'm trying to set the new_foreign_dealer_id = to the user_id inside the old_dealer_id_to_dealer column我正在尝试将new_foreign_dealer_id = 设置为old_dealer_id_to_dealer列中的 user_id

So in the table, the user_id with the value 206 would search for 204 and replace 206's row column with 204's new_foreign_dealer_id因此在表中,值为 206 的 user_id 将搜索 204 并将 206 的行列替换为 204 的new_foreign_dealer_id

Users Table before:之前的用户表:

+---------+-----------------------+-------------------------+
| user_id | new_foreign_dealer_id | old_dealer_id_to_delete |
+---------+-----------------------+-------------------------+
|     200 | 5                     | 02-000012               |
|     204 | 8                     | 02-000097               |
|     206 | 0 (invalid)           | 204 (referneces user_id |
+---------+-----------------------+-------------------------+

Users Table after:之后的用户表:

+---------+-----------------------+-------------------------+
| user_id | new_foreign_dealer_id | old_dealer_id_to_delete |
+---------+-----------------------+-------------------------+
|     200 | 5                     | 02-000012               |
|     204 | 8                     | 02-000097               |
|     206 | 8                     | 204 (referneces user_id |
+---------+-----------------------+-------------------------+

This is the query I tried这是我试过的查询

UPDATE users SET dealer_id_foreign = dealer_id_foreign WHERE dealer_id = user_id

NOTE: The column names in my query are correct.注意:我查询中的列名是正确的。 The ASCII columns are for clarity purposes. ASCII 列是为了清楚起见。

edit: ended up using PHP to achieve this.编辑:最终使用 PHP 来实现这一点。 still interested in a sql answer仍然对 sql 答案感兴趣

http://sqlfiddle.com/#!9/6e5a88/1 http://sqlfiddle.com/#!9/6e5a88/1

UPDATE my_table t
JOIN my_table new
ON t.old_dealer_id_to_delete = new.user_id
   AND t.new_foreign_dealer_id = 0
SET t.new_foreign_dealer_id = new.new_foreign_dealer_id;

Try this I haven't tested it,so please test it first试试这个我还没有测试过,所以请先测试一下

UPDATE users u
    JOIN users ucopy ON u.user_id = ucopy.user_id
SET dealer_id_foreign = dealer_id_foreign
WHERE dealer_id = user_id

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

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