简体   繁体   English

如何在MySQL数据库中设置state与城市之间的关系?

[英]How to set relationship between state and city in MySQL database?

I want to store this type of record我想存储这种类型的记录

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



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

One would expect that several cities can be found in a state (while a city belongs to a unique state).人们会期望在 state 中可以找到几个城市(而一个城市属于一个独特的州)。 To represent that 1-N relationship, you would need two tables: one for the cities and one for the states, where the cities table is a child of the states table (meaning that it has a column that references the id of the state it belongs to):要表示该 1-N 关系,您需要两张表:一张用于城市,一张用于州,其中城市表是 states 表的子表(这意味着它有一个引用 state 的 id 的列属于):

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

Sample create table statements:示例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)
);

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

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