[size=0.833]多表设计的三种关系:
[size=0.833] [size=0.833] 一对多
[size=0.833] 在多的一方创建一个字段,这个字段作为作为外键执向一的一方的主键。
[size=0.833] [size=0.833] 多对多
[size=0.833] 创建一个第三种表,中间表至少需要两个字段分别作为主键指向多对多的双方主键
[size=0.833] [size=0.833] 一对一
[size=0.833] 唯一外键对应:假设一对一的双方式一对多的关系。在多的一方创建外键指向一的一方主键,需要在外键上添加一个unique约束。
[size=0.833] 主键对应:将一对一的双方的主键建立映射
[size=0.833]多表查询的方式:
[size=1.333] 交叉查询:
[size=1.333] select*from A,B; --获得的是两个表的笛卡尔积。
[size=1.333] 内连接:inner join -- inner (可以省略)
[size=0.833] [size=0.833] *显示内连接:select*from A inner join B on 条件;
[size=0.833] *select*from customer c inner join orders o on c.cid = o.cid;
[size=0.833] *隐式内连接:select*from A inner join B on 条件;
[size=1.333] *select*from customer c ,orders o where c.cid;
[size=1.333] 外连接:outer join -- outer(可以省略)
[size=1.333] *左外连接:left outer join -- select*from A left outer join B on 条件;
[size=1.333] *select*from customer c left outer join orders o on c.id = o.id;
[size=1.333] *右外连接:right outer join -- select*from A right outer join B on 条件;
[size=1.333] *select*from customer c right outer join orders o on c.id = o.id;
[size=1.333]
[size=1.333]多表查询的子查询:
[size=0.833] 一个SQL语句查询的过程中需要依赖另一个查询语句。[size=1.333]
[size=0.833] [size=1.167]* select*from customer c,orders o where c.cid = o.cid and c.cid in(select cid from orders where addr like '%海定%')
[size=1.167]
[size=1.167]案例:
[mw_shl_code=sql,true]//创建个表单,对两个表单实行操作
CREATE DATABASE `taiyuan`;
USE `taiyuan`;
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
`dept_id` INT(11) NOT NULL AUTO_INCREMENT,
`dept_name` VARCHAR(16) NOT NULL,
PRIMARY KEY (`dept_id`)
) ENGINE=MYISAM AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
INSERT INTO `department`(`dept_id`,`dept_name`) VALUES (1,'行政部'),(2,'财务部'),(3,'研发部'),(4,'项目部');
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
`emp_id` INT(11) NOT NULL AUTO_INCREMENT,
`emp_name` VARCHAR(16) NOT NULL,
`dept_id` INT(11) NOT NULL,
`emp_wage` DOUBLE NOT NULL,
PRIMARY KEY (`emp_id`)
) ENGINE=MYISAM AUTO_INCREMENT=20 DEFAULT CHARSET=utf8;
INSERT INTO `employee`(`emp_id`,`emp_name`,`dept_id`,`emp_wage`) VALUES (1,'name1',1,6300),(4,'name2',2,4500),(5,'name3',2,5000),(6,'name4',2,4500),(7,'name5',3,9000),(8,'name6',3,9000),(9,'name7',3,10000),(10,'name8',3,10000),(11,'name9',3,20000),(12,'name10',3,18000),(13,'name11',4,60000),(14,'name12',4,10000),(15,'name13',4,50000),(16,'name14',4,60000),(17,'name15',4,20000),(18,'name16',0,2500);
-- 1.查看工资大于5000的员工,并显示所有信息
SELECT
|
|