mysql - 如何根据 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
有什么简单的方法可以实现这一目标吗?
解决方案
如果城市名称是唯一的,则:
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
推荐阅读
- c - 为什么我的线性代数 C 程序会因非方阵而失败?
- json - 如何检索本地 json 数据以将其显示在谷歌地图上?
- azure - 来自联合 Azure 租户的用户可以使用相同的电子邮件向我的 Azure 租户注册吗?
- azure-functions - Azure 函数消耗计划超时
- .net - 在 .net 中使用 SAML 断言准备 Soap 服务
- python - 将数据框中的特定单元格拆分为值列表
- r - 在 r 中置换一列 1000 次
- javafx - JavaFX Slider:如何仅在拖动完成时更改值,同时保持键盘/触摸支持
- visual-studio-2017 - 用于 Visual Studio 2017 的 Eslint
- dart - 如何在 Dart 中编码为 UTF16 Little Endian?