mysql多表查询&原生jdbc
第一章 多表关系实战
1.1 实战:省和市
- 方案1:多张表,一对多
实现省份和城市一对多关系
CREATE TABLE province(
pid INT PRIMARY KEY AUTO_INCREMENT,
pname VARCHAR(20),
description VARCHAR(50)
);
INSERT INTO province(pname,description) VALUES('河北','雾霾'),('内蒙古','草原'),('广东','经济特区');
CREATE TABLE city(
cid INT PRIMARY KEY AUTO_INCREMENT,
cname VARCHAR(20),
description VARCHAR(50),
province_pid INT,
FOREIGN KEY(province_pid) REFERENCES province(pid)
);
INSERT INTO city(cname,description,province_pid) VALUES('石家庄','雾霾之最',1),('承德','避暑山庄',1);
INSERT INTO city(cname,description,province_pid) VALUES('包头','草原钢城',2),('赤峰','红山文化',2);
INSERT INTO city(cname,description,province_pid) VALUES('深圳','经济特区',3),('东莞','服务行业',3);
INSERT INTO city(cname,description,province_pid) VALUES('澳门','博彩娱乐',4);
DELETE FROM province WHERE pname='广东';
- 方案2:一张表,自关联一对多
实现自关联表
CREATE TABLE AREA(
aid INT PRIMARY KEY AUTO_INCREMENT,
aname VARCHAR(20),
description VARCHAR(50),
area_aid INT,
FOREIGN KEY(area_aid) REFERENCES AREA(aid)
);
INSERT INTO AREA(aname,description) VALUES('河北','雾霾'),('内蒙古','草原'),('广东','经济特区');
INSERT INTO AREA(aname,description,area_aid) VALUES('石家庄','雾霾之最',1),('承德','避暑山庄',1);
INSERT INTO AREA(aname,description,area_aid) VALUES('包头','草原钢城',2),('赤峰','红山文化',2);
INSERT INTO AREA(aname,description,area_aid) VALUES('深圳','经济特区',3),('东莞','服务行业',3);
INSERT INTO AREA(aname,description,area_aid) VALUES('香港','旅游购物',4);
第二章 多表查询
提供表结构如下: