首页 > 解决方案 > 如何在 MySQL 数据库中设置州和城市之间的关系?

问题描述

我想存储这种类型的记录

State_Id       state_name
--------------------------
       1       Gujarat
       2       Maharashtra



City_ID         City_name        State_ID
-----------------------------------------
      1         Bhavnagr                1
      2         Rajkot                  1
      1         Mumbai                  2

标签: mysql

解决方案


人们会期望在一个州中可以找到几个城市(而一个城市属于一个独特的州)。为了表示这种 1-N 关系,您需要两张表:一张用于城市,一张用于州,其中城市表是 states 表的子表(这意味着它有一个引用它所在州的 id 的列属于):

states(state_id, state_name, ...)
city(city_id, state_id, city_name, ...)

示例create table语句:

create table states (
    state_id int primary key auto_increment,
    state_name varchar(100)
    -- add more columns here as needed
);

create table cities (
    city_id int primary key auto_increment,
    state_id int not null,
    city_name varchar(100),
    -- add more columns here as needed
    foreign key (state_id) references states(state_id)
);

推荐阅读