简体   繁体   English

MySQL更新列,其值来自第二个表

[英]MySQL update column with value from second table

I would like to replace a users name in one table with their ID, which needs to be referenced from another table. 我想用一个ID替换一个表中的用户名,这需要从另一个表中引用。 For example: 例如:

I have Table A which looks like: 我有表A看起来像:

ID  |  Key  |  Value
---------------------
1   |  name |  Bob
2   |  name |  Bob
3   |  name |  John

And Table B: 和表B:

ID  |  Name
--------------
1   |  Bob
2   |  Rick
3   |  John

I am trying to get Table A to look like: 我想让表A看起来像:

ID  |  Key  |  Value
---------------------
1   |  name |  1
2   |  name |  1
3   |  name |  3

How would I build a query in MySQL to do this? 我如何在MySQL中构建一个查询来执行此操作?

One issue is data types. 一个问题是数据类型。 It is not wise to store numbers as strings. 将数字存储为字符串是不明智的。 But, you can get the values you want doing: 但是,您可以获得您想要的值:

update a join
       b
       on a.value = b.name
    set a.value = b.id;

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

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