mysql - 如何在 MySQL 数据库中设置州和城市之间的关系?
问题描述
我想存储这种类型的记录
State_Id state_name
--------------------------
1 Gujarat
2 Maharashtra
City_ID City_name State_ID
-----------------------------------------
1 Bhavnagr 1
2 Rajkot 1
1 Mumbai 2
解决方案
人们会期望在一个州中可以找到几个城市(而一个城市属于一个独特的州)。为了表示这种 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)
);
推荐阅读
- oracle - 在不同代码块pl sql中填充varray的最佳方法
- node.js - Node.js / Express:是否可以从同一模块为 2 个不同的路由创建 2 个单独的实例?
- mobile - Nuxtjs:将本地主机暴露给外部不起作用
- excel - Excel 公式:如果时间大于 23:30,则返回同一日期的 11:30
- android - 有什么方法可以从应用程序获取 Android Management API 设备 ID
- html - 如何在 snappy pdf 中分页后获取第二页中的哪些内容?
- javascript - 单击按钮1时如何隐藏div2并显示div1角度
- jquery - 如何在 javascript 类中使用 JQuery $(this)
- node.js - 从 Linux 安装时,npm 是否创建了 bin/*.cmd 文件?
- html - Bootstrap 导航栏下拉菜单是否与 github 中的 html 预览兼容?