Verified Commit 8931b72e authored by Kiryuu Sakuya's avatar Kiryuu Sakuya 🎵
Browse files

Finish Homework

parent a4aed8f1
......@@ -148,7 +148,7 @@ ALTER TABLE employee ADD PRIMARY KEY (emp_no);
```mysql
# 没错,是从外键连回主键
ALTER TABLE sales ADD FOREIGN KEY (sale_id) REFERENCES employee(emp_no);
ALTER TABLE sales ADD FOREIGN KEY (sale_id) REFERENCES employee(emp_no) ON UPDATE CASCADE ON DELETE CASCADE;
```
3. 检查约束
......@@ -203,7 +203,7 @@ ALTER TABLE customer ADD PRIMARY KEY (cust_id);
2. 外键约束
```mysql
ALTER TABLE sales ADD FOREIGN KEY (cust_id) REFERENCES customer(cust_id);
ALTER TABLE sales ADD FOREIGN KEY (cust_id) REFERENCES customer(cust_id) ON UPDATE CASCADE ON DELETE CASCADE;
```
#### `sales` 表
......@@ -219,7 +219,7 @@ ALTER TABLE sales ADD PRIMARY KEY (order_no);
> 理论上,但行不通。
```mysql
ALTER TABLE sale_item ADD FOREIGN KEY (order_date) REFERENCES sales(order_date);
ALTER TABLE sale_item ADD FOREIGN KEY (order_date) REFERENCES sales(order_date) ON UPDATE CASCADE ON DELETE CASCADE;
```
3. 唯一约束
......@@ -234,7 +234,7 @@ ALTER TABLE sales ADD UNIQUE(invoice_no);
外键约束
```mysql
ALTER TABLE sales ADD FOREIGN KEY (order_no) REFERENCES sale_item(order_no);
ALTER TABLE sales ADD FOREIGN KEY (order_no) REFERENCES sale_item(order_no) ON UPDATE CASCADE ON DELETE CASCADE;
```
如果输入错误
......@@ -248,7 +248,7 @@ ALTER TABLE sale_item DROP FOREIGN KEY (order_no);
外键约束
```mysql
ALTER TABLE sale_item ADD FOREIGN KEY (prod_id) REFERENCES product(prod_id);
ALTER TABLE sale_item ADD FOREIGN KEY (prod_id) REFERENCES product(prod_id) ON UPDATE CASCADE ON DELETE CASCADE;
```
## 其它
......
......@@ -153,4 +153,24 @@ SELECT * FROM data_tracking;
#### 3. 级联更新:当更新 employee 表中 emp_no 列的值时,同时更新 sales 表中的 sale_id 列的值,并且一次只能更新一行。
#### 4. 对 employee 表写一个 UPDATE 触发器。
\ No newline at end of file
```mysql
DELIMITER //
CREATE TRIGGER change_employee_emp_id_and_sale_id AFTER UPDATE ON employee FOR EACH ROW
BEGIN
IF (New.emp_no != Old.emp_no) THEN
UPDATE sales SET sale_id = New.emp_no WHERE sale_id = Old.emp_no;
END IF;
END//
DELIMITER ;
```
临时关闭主从键检测
```mysql
SET FOREIGN_KEY_CHECKS=0; -- to disable them
SET FOREIGN_KEY_CHECKS=1; -- to re-enable them
```
#### 4. 对 employee 表写一个 UPDATE 触发器。
在 Trigger 里,不能显示消息。
\ No newline at end of file
......@@ -6,7 +6,7 @@
### 示例代码
#### 1. 数据库需求分
#### 1. 数据库需求分
#### 2. 数据库结构设计
......@@ -20,8 +20,32 @@ mysqldump -u root -p studentdb > Test.sql
##### b. 数据转储
就是备份。
##### c. 登记日志文件
```mysql
# 默认日志级别定义在全局级别下
SHOW GLOBAL VARIABLES LIKE '%log%';
# `general_log` 定义查询日志是否开启
# `log` 定义是否开启日志(所有)
# `slow_query_log` 慢查询日志记录执行时间,可以查找哪些语句的执行效率很低,以便进行优化
```
可以编辑 `my.cnf` 来开启慢查询日志
```
[mysqld]
slow_query_log = 1
```
或者使用变量
```
SET GLOBAL slow_query_log = 1;
SET GLOBAL long_query_time = 0.001;
# 更改时间,如只在当前会话生效则为 SESSION
##### d. 数据恢复
```mysql
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment