数据库:如何创建更新级联表和查询数据?

时间:2014-06-28 12:54:11

标签: mysql database cascade

我想创建一个有两个表的数据库。我想在两个表之间创建更新级联关系。如果在EMPLOYEE中更改了SNAME,那么WORKREPORT也会更改其SNAME。

EMPLOYEE:
SNO      SNAME           SPASSWORD     SEX      BDATE           HEIGHT    BTITLE
2014      boss            12345        male      1987-06-02       180       Manager
2015      Tom             1234567      male      1987-06-05       180       Employee


WORKREPORT
   SNO       SNAME             SDATA         SCHECKLIST       SIMAGE
   2014      boss            1987-06-02      abc               afafafaf
   2015      Tom             1987-06-05      affafa            afafafaf

我的代码效果非常好。我的问题在于:我不知道如何只从员工那里查询员工的信息(而不是经理),假设有很多员工。我该怎么办?我是否正确设计" WORKREPORT"? 这是我的代码:

CREATE database  if not exists cm360_cm360_1;
use cm360_cm360_1;
CREATE TABLE IF NOT EXISTS EMPLOYEE(SNO VARCHAR(7) NOT NULL,  SNAME VARCHAR(8) NOT NULL,  SPASSWORD VARCHAR(11) NOT NULL,SEX VARCHAR(8) NOT NULL,  BDATE DATETIME NOT NULL,  HEIGHT DEC(5,2) DEFAULT 000.00,BTitle VARCHAR(15) NOT NULL,  PRIMARY KEY(SNO), UNIQUE KEY (SNAME))ENGINE=InnoDB ;

SET SQL_SAFE_UPDATES=0;
INSERT INTO EMPLOYEE VALUES (2014,'boss','12345','male','2014-6-10 11:00:00',160.00,'Manager');
INSERT INTO EMPLOYEE VALUES (2015,'Tom','1234567','male','2014-6-10 12:00:00',160.00,'Employee');
SELECT * FROM EMPLOYEE;


CREATE TABLE IF NOT EXISTS WORKREPORT(SNO VARCHAR(7) NOT NULL,  SNAME VARCHAR(8) NOT NULL,SDATA DATETIME ,  SCHECKLIST VARCHAR(150),SIMAGE VARCHAR(20),FOREIGN KEY (SNO) REFERENCES EMPLOYEE (SNO) ON UPDATE CASCADE,FOREIGN KEY(SNAME) REFERENCES EMPLOYEE (SNAME) ON UPDATE CASCADE ) ENGINE=InnoDB;


INSERT INTO WORKREPORT VALUES (2014,'boss',' 2014-6-10 14:38:59','abc','afdsfdfds');
INSERT INTO WORKREPORT VALUES (2015,'Tom',' 2014-6-10 15:38:59','abc','afdsfdfds');
SELECT * FROM  WORKREPORT order by SDATA ASC;

UPDATE WORKREPORT SET SCHECKLIST='elevator;floor' WHERE SNAME='hanlu2';
delete from workreport WHERE  SIMAGE='N/A' AND SNAME='enlan';

2 个答案:

答案 0 :(得分:1)

如果您想获取员工的WORKREPORT信息,请查看以下信息。

SELECT WORKREPORT.* 
FROM WORKREPORT, EMPLOYEE 
WHERE EMPLOYEE.SNO = WORKREPORT.SNO 
AND EMPLOYEE.BTITLE = "Employee"

答案 1 :(得分:1)

如果您只想获取所有员工信息,可以JOIN SNO和/或SNAME上的两个表,因为您在这些列上有FK关系,并按条件BTITLE不应该是MANAGER

select e.*
from employee e
join workreport w on e.SNO = w.SNO
and e.SNAME = w.SNAME
and e.BTITLE <> 'Manager'