CREATE TABLE emp(
empno INT(4) NOT NULL COMMENT '员工编号',
ename VARCHAR(10) COMMENT '员工名字',
job VARCHAR(10) COMMENT '职位',
mgr INT(4) COMMENT '上司',
hiredate DATE COMMENT '入职时间',
sal INT(7) COMMENT '基本工资',
comm INT(7) COMMENT '补贴',
deptno INT(2) COMMENT '所属部门编号'
);
mysql> alter table emp add primary key(empno);
Query OK, 0 rows affected (0.01 sec)
Records: 0 Duplicates: 0 Warnings: 0
在MySQL中,可以使用alter table 语句来添加外键约束。以下是基本的语法:
ALTER TABLE table_name
ADD FOREIGN KEY (column_name) REFERENCES other_table(other_column);
在这个语句中:
- table_name是你想要添加外键的表的名称。
- column_name是你想要设置为外键的列的名称。
- other_table是包含外键引用的表的名称。
- other_column是在other_table中的列的名称。
ALTER TABLE emp ADD CONSTRAINT f_ed_key FOREIGN KEY (deptno) REFERENCES dept(deptno);
INSERT INTO `emp` VALUES('7369','张倩','办事员','7902','2002-12-17','820',NULL,'20');
INSERT INTO `emp` VALUES('7499','刘博','售货员','7698','1992-02-20','1900','300','30');
INSERT INTO `emp` VALUES('7521','李兴','售货员','7698','1995-07-22','1250','500','30');
INSERT INTO `emp` VALUES('7566','李雷','人事部长','7839','1991-04-02','975',NULL,'20');
INSERT INTO `emp` VALUES('7654','刘浩','售货员','7698','1991-09-28','1250','1400','30');
INSERT INTO `emp` VALUES('7698','刘涛','销售部长','7839','1997-05-01','2850',NULL,'30');
INSERT INTO `emp` VALUES('7782','华仔','人事部长','7839','1995-06-09','2450',NULL,'10');
INSERT INTO `emp` VALUES('7788','张飞','人事专员','7566','1998-04-19','3000',NULL,'20');
INSERT INTO `emp` VALUES('7839','马晓云','董事长',NULL,'1991-11-17','5000',NULL,'10');
INSERT INTO `emp` VALUES('7844','马琪','售货员','7698','1996-09-08','1500','0','30');
INSERT INTO `emp` VALUES('7876','李涵','办事员','7788','1997-05-23','1100',NULL,'20');
INSERT INTO `emp` VALUES('7900','李小涵','销售员','7698','1993-2-13','950',NULL,'30');
INSERT INTO `emp` VALUES('7902','张三','人事组长','7566','1992-10-08','3000',NULL,'20');
INSERT INTO `emp` VALUES('7934','张三丰','人事长','7782','1997-06-23','1300',NULL,'10');
mysql> select * from emp;
CREATE TABLE salgrade(
grade INT (10) COMMENT '工资等级',
losal INT (10) COMMENT '最低限额',
hisal INT (10) COMMENT '最高限额'
);
INSERT INTO salgrade (grade, losal, hisal)VALUES (1, 700, 1200);
INSERT INTO salgrade (grade, losal, hisal)VALUES (2, 1201, 1400);
INSERT INTO salgrade (grade, losal, hisal)VALUES (3, 1401, 2000);
INSERT INTO salgrade (grade, losal, hisal)VALUES (4, 2001, 3000);
INSERT INTO salgrade (grade, losal, hisal)VALUES (5, 3001, 9999);
mysql> select * from salgrade;
在进行 join 操作时,可以使用 where 子句来添加额外的过滤条件,或者使用group by 、having 和order by 子句来进行数据分组和排序。
mysql> select grade 等级,count(*) 员工人数 from emp e join salgrade s
where e.sal>=losal and e.sal <=hisal group by grade;
join salgrade s on e.sal between s.losal and s.hisal: 这部分是连接 emp 表和 salgrade 表。连接条件是 emp表的sal字段值在 salgrade 表 的 losal 和 hisal 字段值之间。
mysql> select e.deptno 部门编号, avg(grade) 平均工资等级 from emp e join salgrade s on e.sal between s.losal and s.hisal group by e.deptno;