1準備
1.1準備測試數據
- 將sql文件導入到mysql中
- source soctt_data.sql
2交叉連接(笛卡爾積)
- select e.*, k.* from employee e cross join lvke k;
3自連接(等值連接)
- select e.,c. from employee e inner join class c on e.id=c.id;
- 其中的inner可省略
3.1總結:與oracle的不同
逗號–改變爲–>inner join
where–改變爲–>on
4外連接
4.1左外連接
select e.,c. from employee e left outer join class c on e.id=c.id;
4.2右外連接
select e.,c. from employee e right outer join class c on e.id=c.id;
- 總結:
- 外連接取值是與關係表達式=左右的位置無關,取值跟from後表的書寫順序有關
- xx left outer join yyy則爲取出xxx內容
- xxx left outer join yyy則爲取出yyy內容
5 小結
- 因爲mysql 不支持使用nvl
- 所以使用 ifnull
- ifnull(e.name,‘his wife’)
6表的約束
6.1概念
- 定義主鍵約束:不允許爲空,不允許重複:primary key
- 定義主鍵自動增長:auto_increment
- 定義唯一約束:unique
- 定義非空約束: not null
- 定義外鍵約束 :constraint ordersid_FK foreign key(ordersid) references orders(id)
- 刪除主鍵: alter table tablename drop primary key;
測試準備
create table class1(
id int PRIMARY key auto_increment,
name VARCHAR(20) UNIQUE
);
create table student (
id int PRIMARY key auto_increment,
name VARCHAR(20) UNIQUE,
password VARCHAR(15) not null,
class1id int,
constraint stu_class1id_FK foreign key(class1id) references class1(id)
);
6.3測試
- 主鍵自增長
insert into class1(name) values('音樂');
insert into class1(name) values('體育');
- 賦值主鍵
insert into class1(id,name) values(5,'美術');
insert into class1(name) values('社會');
- 注意:要插入的是部分列 一定要在class表名後面寫上列名 表示要插入那些列 由於class id爲主鍵 所以不用顯示插入 mysql會自動插入 而且會自動增長 保證不重複。
- insert into student(id,name,password,class1id) values(null,'小紅','12345',1);
-
總結 若給主鍵插入一個null ,mysql會自動插入一個有效值 所以mysql主鍵肯定不爲空
-
測試主鍵的唯一性、
- insert into student(id,name,password,class1id) values(1,'小化','12345',1);
- 1062 - Duplicate entry '1' for key 'PRIMARY'
- 測試name唯一性
- insert into student(name,password,class1id) values('小化','12345',1);
- 1062 - Duplicate entry '小化' for key 'name'
- 測試password非空性
- insert into student(name,password,class1id) values('小路',null,1);
- 1048 - Column 'password' cannot be null
- 測試classid外鍵約束
- insert into student(name,password,class1id) values('小往','12345',10);
- > 1452 - Cannot add or update a child row: a foreign key constraint fails (`lvke`.`student`, CONSTRAINT `stu_class1id_FK` FOREIGN KEY (`class1id`) REFERENCES `class1` (`id`))