※表与表之间的关系
1、一对一
需要两个表。当然做项目时为了省空间,通常只建一个表,如果要实现一对一的查询,可以建两个视图。示例如下:
1)建物理表,初始化数据
CREATE TABLE person(
id INT,
NAME VARCHAR(10),
sex CHAR(1),
wife INT,
husband INT
);
INSERT INTO person VALUES(1,'小花','0',0,3);
INSERT INTO person VALUES(2,'玉芬','0',0,4);
INSERT INTO person VALUES(3,'张三','1',1,0);
INSERT INTO person VALUES(4,'李四','1',2,0);
INSERT INTO person VALUES(5,'王五','1',0,0);
2) 建立两个视图
create view women as select * from person where sex='0';
create view men as select * from person where sex='1';
3) 查询夫妻信息
//旧版本
SELECT women.name AS 妻子, men.name AS 丈夫 FROM women, men WHERE women.husband = men.id;
//采用内联接--98以后的新方式--效率更高
SELECT women.name AS 妻子, men.name AS 丈夫 FROM women INNER JOIN men ON women.husband = men.id;
<pre name="code" class="sql">3、多对多
数据库设计分析
※案例
数据库设计(一对一,一对多,多对多)关联查询
最新推荐文章于 2024-09-18 15:29:51 发布