MySQL 自关联查询
2024-10-19 04:25:57
定义表areas,结构如下
- id
- atitle
- pid
- 因为省没有所属的省份,所以可以填写为null
- 城市所属的省份pid,填写省所对应的编号id
- 这就是自关联,表中的某一列,关联了这个表中的另外一列,但是它们的业务逻辑含义是不一样的,城市信息的pid引用的是省信息的id
- 在这个表中,结构不变,可以添加区县、乡镇街道、村社区等信息
- 创建areas表的语句如下:
create table areas(
id int primary key,
atitle varchar(20),
pid int,
foreign key(pid) references areas(id)
);
- 查询一共有多少个省
- 查询省的名称为“山西省”的所有城市
select city.* from areas as city
inner join areas as province on city.pid=province.id
where province.atitle='山西省';
- 查询市的名称为“广州市”的所有区县
select dis.*,dis2.* from areas as dis
inner join areas as city on city.id=dis.pid
left join areas as dis2 on dis.id=dis2.pid
where city.atitle='广州市';
最新文章
- UICollectionLayout布局 —— UIKit之学习UICollectionView记录二《流水布局》
- <;十六>;JDBC_使用 DBUtils 编写通用的DAO
- 构建 iOS 风格移动 Web 应用程序的8款开发框架
- Tomcat下安装solr6.x
- 乱谈Qt事件循环嵌套
- 理解C#中的继承
- linq to sql简单使用
- 通过xib创建控制器
- at 定时任务
- virtualbox下正确虚拟机修改设备名称
- DOM操作中,getElementByXXXX 和 querySelector 的区别
- poj3270 &;&; poj 1026(置换问题)
- pandas模块实现小爬虫功能-转载
- eMMC基础技术4:eMMC command
- 一种简单的生产环境部署Node.js程序方法
- Codeforces Round #495 (Div. 2) C. Sonya and Robots
- Rabbit and Grass
- js判断是否手机自动跳转移动端
- Can you answer these queries?---hdu4027
- jQuery 概述