现有一个商店的数据库,记录顾客及其购物情况,由下面三个表组成: 商品product(商品号productid,商品名productname,单价unitprice,商品类别category,供应商provider); 顾客customer(顾客号customerid,姓名name,住址location); 购买purcase(顾客号customerid,商品号productid,购买数量quantity); 试用SQL语言完成下列功能: 1 建表,在定义中要求声明: (1)每个表有主键; (2)顾客的姓名和商品名不能为空值; (3)单价必须大于0,购买数量必须再0到20之间; 2 往表中插入数据: 商品(M01,佳洁士,8.00,牙膏,宝洁; M02,高露洁,6.50,牙膏,高露洁; M03,洁诺,5.00,牙膏,联合利华; M04,舒肤佳,3.00,香皂,宝洁; M05,夏士莲,5.00,香皂,联合利华; M06,雕牌,2.50,洗衣粉,纳爱斯 M07,中华,3.50,牙膏,联合利华; M08,汰渍,3.00,洗衣粉,宝洁; M09,碧浪,4.00,洗衣粉,宝洁;) 顾客(C01,Dennis,海淀; C02,John,朝阳; C03,Tom,东城; C04,Jenny,东城; C05,Rick,西城;) 购买(C01,M01,3; C01,M05,2; C01,M08,2; C02,M02,5; C02,M06,4; C03,M01,1; C03,M05,1; C03,M06,3; C03,M08,1; C04,M03,7; C04,M04,3; C05,M06,2; C05,M07,8;) 商品有9 条,顾客有5条,购买有13条
时间: 2024-02-10 22:22:11 浏览: 170
数据库demo,里面有个商品表
以下是SQL语言实现上述功能的代码:
1. 建表
```sql
-- 商品表
CREATE TABLE product (
productid CHAR(3) PRIMARY KEY,
productname VARCHAR(20) NOT NULL,
unitprice DECIMAL(5,2) CHECK(unitprice > 0),
category VARCHAR(10),
provider VARCHAR(20)
);
-- 顾客表
CREATE TABLE customer (
customerid CHAR(3) PRIMARY KEY,
name VARCHAR(20) NOT NULL,
location VARCHAR(20)
);
-- 购买表
CREATE TABLE purchase (
customerid CHAR(3),
productid CHAR(3),
quantity INT CHECK(quantity >= 0 AND quantity <= 20),
PRIMARY KEY (customerid, productid),
FOREIGN KEY (customerid) REFERENCES customer(customerid),
FOREIGN KEY (productid) REFERENCES product(productid)
);
```
2. 插入数据
```sql
-- 商品数据
INSERT INTO product VALUES
('M01', '佳洁士', 8.00, '牙膏', '宝洁'),
('M02', '高露洁', 6.50, '牙膏', '高露洁'),
('M03', '洁诺', 5.00, '牙膏', '联合利华'),
('M04', '舒肤佳', 3.00, '香皂', '宝洁'),
('M05', '夏士莲', 5.00, '香皂', '联合利华'),
('M06', '雕牌', 2.50, '洗衣粉', '纳爱斯'),
('M07', '中华', 3.50, '牙膏', '联合利华'),
('M08', '汰渍', 3.00, '洗衣粉', '宝洁'),
('M09', '碧浪', 4.00, '洗衣粉', '宝洁');
-- 顾客数据
INSERT INTO customer VALUES
('C01', 'Dennis', '海淀'),
('C02', 'John', '朝阳'),
('C03', 'Tom', '东城'),
('C04', 'Jenny', '东城'),
('C05', 'Rick', '西城');
-- 购买数据
INSERT INTO purchase VALUES
('C01', 'M01', 3),
('C01', 'M05', 2),
('C01', 'M08', 2),
('C02', 'M02', 5),
('C02', 'M06', 4),
('C03', 'M01', 1),
('C03', 'M05', 1),
('C03', 'M06', 3),
('C03', 'M08', 1),
('C04', 'M03', 7),
('C04', 'M04', 3),
('C05', 'M06', 2),
('C05', 'M07', 8);
```
阅读全文