我有一个表“位置”,其结构如下
CREATE TABLE IF NOT EXISTS `locations` (
`id` int(11) NOT NULL,
`city_code` int(11) NOT NULL,
`city_name` varchar(100) NOT NULL,
`state_name` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=154809 ;
我想将其分成两个表:
状态包含以下字段
id,
state_name
和带有以下字段的城市
id,
state_id,
city_name,
city_code
如何在 mysql 中执行此操作。
最佳答案
创建所需的表,例如
create table states (id int not null auto_increment primary key,
state_name varchar(100) not null);
create table cities (id int not null auto_increment primary key,
state_id int not null,
`city_code` int(11) NOT NULL,
`city_name` varchar(100) NOT NULL,
foreign key (state_id) references states(id));
插入相应的数据
insert into states (state_name)
select state_name from locations;
insert into cities (state_id, `city_code`, `city_name`)
select s.state_id, l.`city_code`, l.`city_name`
from locations l
join states s on s.state_name = l.state_name;
关于php - 如何在mysql中使用外键state_id将表位置拆分为两个表状态,城市?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34556551/