MySQL创建一个数据库图书管理.库:创建,使用,备份,还原,分离,附加 2.表:创建表并添加约束(3张表)、查看表结构、删除 3.表结构:增加字段,改字段名称,类型长度,类型更改,删除字段,表名 4.增加主键自增,创建规则,绑定,解除,删除规则 5.通过命令添加约束,删除约束*
时间: 2023-09-29 18:06:39 浏览: 106
1. 创建、使用、备份、还原、分离、附加数据库
创建数据库:
```
CREATE DATABASE book_management;
```
使用数据库:
```
USE book_management;
```
备份数据库:
```
mysqldump -u root -p book_management > book_management_backup.sql
```
还原数据库:
```
mysql -u root -p book_management < book_management_backup.sql
```
分离数据库:
```
DROP DATABASE book_management;
```
附加数据库:
```
ALTER DATABASE book_management ADD FILE ('/path/to/new/file');
```
2. 创建表并添加约束(3张表)、查看表结构、删除
创建图书表:
```
CREATE TABLE books (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
author VARCHAR(255) NOT NULL,
isbn VARCHAR(13) NOT NULL,
price DECIMAL(10, 2) NOT NULL,
published_date DATE NOT NULL,
CONSTRAINT uc_books UNIQUE (isbn)
);
```
创建读者表:
```
CREATE TABLE readers (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
phone VARCHAR(20) NOT NULL,
address VARCHAR(255) NOT NULL,
CONSTRAINT uc_readers UNIQUE (email, phone)
);
```
创建借阅记录表:
```
CREATE TABLE borrow_records (
id INT AUTO_INCREMENT PRIMARY KEY,
book_id INT NOT NULL,
reader_id INT NOT NULL,
borrow_date DATE NOT NULL,
return_date DATE,
CONSTRAINT fk_book FOREIGN KEY (book_id) REFERENCES books (id),
CONSTRAINT fk_reader FOREIGN KEY (reader_id) REFERENCES readers (id)
);
```
查看表结构:
```
DESCRIBE books;
DESCRIBE readers;
DESCRIBE borrow_records;
```
删除表:
```
DROP TABLE books;
DROP TABLE readers;
DROP TABLE borrow_records;
```
3. 表结构:增加字段,改字段名称,类型长度,类型更改,删除字段,表名
添加字段:
```
ALTER TABLE books ADD COLUMN language VARCHAR(255) NOT NULL AFTER published_date;
```
改字段名称:
```
ALTER TABLE books CHANGE COLUMN published_date publish_date DATE NOT NULL;
```
类型长度:
```
ALTER TABLE books MODIFY COLUMN price DECIMAL(12, 2) NOT NULL;
```
类型更改:
```
ALTER TABLE books MODIFY COLUMN isbn BIGINT NOT NULL;
```
删除字段:
```
ALTER TABLE books DROP COLUMN language;
```
表名:
```
ALTER TABLE books RENAME TO new_books;
```
4. 增加主键自增,创建规则,绑定,解除,删除规则
增加主键自增:
```
ALTER TABLE books MODIFY COLUMN id INT AUTO_INCREMENT PRIMARY KEY;
```
创建规则:
```
CREATE TRIGGER tr_borrow_record BEFORE INSERT ON borrow_records
FOR EACH ROW
BEGIN
IF NEW.return_date < NEW.borrow_date THEN
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Return date must be after borrow date.';
END IF;
END;
```
绑定规则:
```
ALTER TABLE borrow_records ENABLE TRIGGER tr_borrow_record;
```
解除规则:
```
ALTER TABLE borrow_records DISABLE TRIGGER tr_borrow_record;
```
删除规则:
```
DROP TRIGGER tr_borrow_record;
```
5. 通过命令添加约束,删除约束
添加约束:
```
ALTER TABLE books ADD CONSTRAINT ck_price CHECK (price > 0);
```
删除约束:
```
ALTER TABLE books DROP CONSTRAINT ck_price;
```
阅读全文