首页 > 解决方案 > 如何根据 Mysql 中另一个表的值在一个表中添加新列?

问题描述

当前的

table_users - user_name, city_name
table_cities - city_id, city_name

我想在 table_users 中添加一个名为 city_id 的新列,其中 city_id 需要从 table_cities 中获取。

预期的

table_users - user_name, city_name, city_id (value of this needs to get from table_cities)
table_cities - city_id, city_name

有什么简单的方法可以实现这一目标吗?

标签: mysql

解决方案


如果城市名称是唯一的,则:

ALTER TABLE table_users ADD COLUMN city_id INT NULL;

UPDATE table_users
SET city_id = (SELECT city_id 
               FROM table_cities 
               WHERE table_users.city_name = table_cities.city_name
               LIMIT 1);

ALTER TABLE table_users
ADD CONSTRAINT FK_table_cities
FOREIGN KEY (city_id) REFERENCES table_cities(city_id); 

ALTER TABLE table_users MODIFY city_id INT NOT NULL; -- optional

推荐阅读