用sql语言写一个图书借阅关系系统
时间: 2023-12-29 11:17:37 浏览: 43
假设有三个表,分别为图书表(books)、读者表(readers)和借阅记录表(borrow_records),其结构如下:
books表:
| 字段名 | 数据类型 | 说明 |
| ------ | -------- | --------------- |
| id | int | 图书ID,主键 |
| name | varchar | 图书名称 |
| author | varchar | 图书作者 |
| status | int | 图书状态(0/1) |
readers表:
| 字段名 | 数据类型 | 说明 |
| ------ | -------- | ------------------ |
| id | int | 读者ID,主键 |
| name | varchar | 读者姓名 |
| gender | int | 读者性别(0/1) |
| phone | varchar | 读者联系电话 |
| email | varchar | 读者电子邮件地址 |
borrow_records表:
| 字段名 | 数据类型 | 说明 |
| ----------- | -------- | ----------------------- |
| id | int | 借阅记录ID,主键 |
| reader_id | int | 借阅者ID,外键关联readers表 |
| book_id | int | 图书ID,外键关联books表 |
| borrow_date | date | 借阅日期 |
| return_date | date | 归还日期 |
其中,books表中的status字段表示图书的借阅状态,0表示未借出,1表示已借出。
创建表的SQL语句如下:
```
CREATE TABLE books (
id INT PRIMARY KEY,
name VARCHAR(50),
author VARCHAR(50),
status INT
);
CREATE TABLE readers (
id INT PRIMARY KEY,
name VARCHAR(50),
gender INT,
phone VARCHAR(20),
email VARCHAR(50)
);
CREATE TABLE borrow_records (
id INT PRIMARY KEY,
reader_id INT,
book_id INT,
borrow_date DATE,
return_date DATE,
FOREIGN KEY (reader_id) REFERENCES readers(id),
FOREIGN KEY (book_id) REFERENCES books(id)
);
```
插入数据的SQL语句如下:
```
INSERT INTO books (id, name, author, status) VALUES (1, 'Java编程思想', 'Bruce Eckel', 0);
INSERT INTO books (id, name, author, status) VALUES (2, '深入理解Java虚拟机', '周志明', 1);
INSERT INTO books (id, name, author, status) VALUES (3, '高性能MySQL', 'Baron Schwartz', 0);
INSERT INTO readers (id, name, gender, phone, email) VALUES (1, '张三', 1, '13888888888', 'zhangsan@example.com');
INSERT INTO readers (id, name, gender, phone, email) VALUES (2, '李四', 0, '13999999999', 'lisi@example.com');
INSERT INTO readers (id, name, gender, phone, email) VALUES (3, '王五', 1, '13666666666', 'wangwu@example.com');
INSERT INTO borrow_records (id, reader_id, book_id, borrow_date, return_date) VALUES (1, 1, 2, '2021-01-01', '2021-01-15');
INSERT INTO borrow_records (id, reader_id, book_id, borrow_date, return_date) VALUES (2, 2, 1, '2021-02-01', '2021-02-15');
INSERT INTO borrow_records (id, reader_id, book_id, borrow_date, return_date) VALUES (3, 3, 2, '2021-03-01', NULL);
```
查询所有借阅记录的SQL语句如下:
```
SELECT r.name AS reader_name, b.name AS book_name, br.borrow_date, br.return_date
FROM borrow_records br
JOIN readers r ON br.reader_id = r.id
JOIN books b ON br.book_id = b.id;
```
查询某个读者的借阅记录的SQL语句如下:
```
SELECT b.name AS book_name, br.borrow_date, br.return_date
FROM borrow_records br
JOIN books b ON br.book_id = b.id
WHERE br.reader_id = 1;
```
查询某本图书的借阅记录的SQL语句如下:
```
SELECT r.name AS reader_name, br.borrow_date, br.return_date
FROM borrow_records br
JOIN readers r ON br.reader_id = r.id
WHERE br.book_id = 2;
```
更新某个借阅记录的归还日期的SQL语句如下:
```
UPDATE borrow_records SET return_date = '2021-04-01' WHERE id = 3;
```
以上是一个简单的图书借阅关系系统的SQL语言实现,实际应用中可能需要更多的功能和表结构设计。
阅读全文