问题:
假设某建筑公司要设计一个数据库。公司的业务规则概括说明如下:
公司承担多个工程项目,每一项工程有:工程号、工程名称、施工人员等
公司有多名职工,每一名职工有:职工号、姓名、性别、职务(工程师、技术员)等
公司按照工时和小时工资率支付工资,小时工资率由职工的职务决定(例如,技术员的小时工资率与工程师不同)
财务表
分析:
表中包含大量冗余数据,可能会导致数据异常:
更新异常
添加异常
删除异常
设计1:
设计2:
建表如下:
CREATE DATABASE mysql_316;
#工程表
CREATE TABLE project (
pid INT PRIMARY KEY AUTO_INCREMENT,
pno VARCHAR (5) UNIQUE NOT NULL,
pname VARCHAR (10) NOT NULL
) ;
#职务表
CREATE TABLE post (
pid INT PRIMARY KEY AUTO_INCREMENT,
ppost VARCHAR (10) UNIQUE NOT NULL,
psalary INT NOT NULL
) ;
#职工表
CREATE TABLE employee (
eid INT PRIMARY KEY AUTO_INCREMENT,
eno INT UNIQUE NOT NULL,
ename VARCHAR (10) NOT NULL,
epost VARCHAR (10) NOT NULL,
FOREIGN KEY (epost) REFERENCES post (ppost) ON DELETE CASCADE ON UPDATE CASCADE
)
#项目工时表
CREATE TABLE item (
iid INT PRIMARY KEY AUTO_INCREMENT,
ipno VARCHAR (5) NOT NULL,
ieno INT NOT NULL,
itime INT NOT NULL,
FOREIGN KEY (ipno) REFERENCES project (pno) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (ieno) REFERENCES employee (eno) ON DELETE CASCADE ON UPDATE CASCADE
) ;
插入数据
#向工程表中插入数据
INSERT INTO project (pno, pname)
VALUES
('A1', '花园大厦'),
('A2', '立交桥'),
('A3', '临江饭店') ;
SELECT * FROM project;
#向职务表中插入数据
INSERT INTO post (ppost, psalary)
VALUES
('工程师', 65),
('技术员', 60),
('律师', 60),
('工人', 55) ;
SELECT * FROM post;
#向职工表中插入数据
INSERT INTO employee (eno, ename, epost)
VALUES
(1001, '齐光明', '工程师'),
(1002, '李思岐', '技术员'),
(1003, '鞠明亮', '工人'),
(1004, '葛宇宏', '律师');
SELECT * FROM employee;
#向项目工时表中插入数据
INSERT INTO item (ipno, ieno, itime)
VALUES
('A1',1001,13),
('A1',1002,16),
('A1',1004,19),
('A2',1001,13),
('A2',1003,17),
('A3',1002,18),
('A3',1004,14);
SELECT * FROM item;
操作
显示原表每个列信息
SELECT
project.pno 工程号,
project.pname 工程名,
employee.eid 职工号,
employee.ename 姓名,
employee.epost 职务,
post.psalary 小时率,
item.itime 小时,
post.psalary * item.itime 实发工资
FROM
project,
post,
employee,
item
WHERE item.ipno = project.pno
AND item.ieno = employee.eno
AND employee.epost = post.ppost ;
按照工程号查询每个工程的总开销
SELECT project.pno 工程号,
SUM(post.psalary * item.itime) 合计
FROM
project,
post,
employee,
item
WHERE item.ipno = project.pno
AND item.ieno = employee.eno
AND employee.epost = post.ppost GROUP BY project.pno ;