MySQL的使用
数据库三层结构
- 所谓安装Mysql数据库,就是在主机安装一个数据库管理系统(DBMS),这个管理程序可以管理多个数据库.DBMS(database manage system)
- 一个数据库中可以创建多个表,以保存数据.
- 数据库管理系统(DBMS),数据库和表的关系如图所示:
数据在数据库中的存储方式
SQL语句分类
- DDL: 数据定义语句 [CREATE 表,库…]
- DML: 数据操作语句 [增加 insert,修改 update,删除 delete]
- DQL: 数据查询语句 [select]
- DCL: 数据控制语句 [管理数据库:比如用户权限 grant revoke]
创建数据库
CREATE DATABASE db01;
CREATE DATABASE db02 CHARACTER SET utf8
CREATE DATABASE db03 CHARACTER SET utf8 COLLATE utf8_bin
查看,删除数据库
SHOW DATABASES
SHOW CREATE DATABASE db01
DROP DATABASE db01
备份恢复数据库
mysqldump -u root -p -B db02 db03 > F:\zxkworkspace\mysql\bak.sql
mysqldump -u -root -p db02 t1 > f:\zxkworkspace\mysql\bak1.sql
mysql -u root -p
source F:\zxkworkspace\mysql\bak.sql
quit
创建表
CREATE TABLE `user` (
id INT,
`name` VARCHAR(255),
`password` VARCHAR(255),
`birthday` DATE)
CHARACTER SET utf8 COLLATE utf8_bin ENGINE INNODB;
Mysql常用数据类型(列类型)
数值型(整数)的基本使用
CREATE TABLE t3(
id TINYINT);
INSERT INTO t3 VALUES(-128);
SELECT * FROM t3
CREATE TABLE t4(
id TINYINT UNSIGNED);
INSERT INTO t4 VALUES(1);
INSERT INTO t4 VALUES(-5);
SELECT * FROM t4
数值型(bit)的使用
CREATE TABLE t05(num BIT(8));
INSERT INTO t05 VALUES(255);
SELECT * FROM t05;
SELECT * FROM t05 WHERE num=255;
数值型(小数)的基本使用
CREATE TABLE t06(
num1 FLOAT,
num2 DOUBLE,
num3 DECIMAL(30,20));
INSERT INTO t06 VALUES(88.12345678912345,88.12345678912345,88.12345678912345);
SELECT * FROM t06;
CREATE TABLE t07(num DECIMAL(65));
INSERT INTO t07 VALUES(8999999933338388388383838838383009338388383838383838383);
SELECT * FROM t07;
CREATE TABLE t08(num BIGINT);
INSERT INTO t08 VALUES(8999999933338388388383838838383009338388383838383838383);
SELECT * FROM t08;
字符串的基本使用
CREATE TABLE t09(`name` CHAR(255));
CREATE TABLE t10(`name` VARCHAR(21844));
CREATE TABLE t10(`name` VARCHAR(32766)) CHARSET gbk;
DROP TABLE t10;
使用细节:
CREATE TABLE t11(`name` CHAR(4));
INSERT INTO t11 VALUES('韩好');
SELECT * FROM t11;
CREATE TABLE t12(`name` VARCHAR(4));
INSERT INTO t12 VALUES('韩好');
SELECT * FROM t12;
CREATE TABLE t13(content TEXT ,content2 MEDIUMTEXT,content3 LONGTEXT);
INSERT INTO t13 VALUES('韩顺平教育', '韩顺平教育100', '韩顺平教育1000~~');
SELECT * FROM t13;
日期类型的基本使用
CREATE TABLE t14 (
birthday DATE,
job_time DATETIME,
login_time TIMESTAMP
NOT NULL DEFAULT CURRENT_TIMESTAMP
ON UPDATE CURRENT_TIMESTAMP);
SELECT * FROM t14;
INSERT INTO t14(birthday,job_time)
VALUES('2022-11-11','2022-11-11 10:10:10');
操作表语句
创建表
CREATE TABLE `emp`(
id INT,
`name` VARCHAR(32),
sex CHAR(1),
birthday DATE,
entry_date DATE,
job VARCHAR(32),
salary DOUBLE,
resume TEXT) CHARSET utf8 COLLATE utf8_bin ENGINE INNODB;
DROP TABLE `emp`;
SELECT * FROM `emp`;
INSERT INTO `emp`
VALUES(100,'小妖怪','男','2000-11-11',
'2010-11-10 11:11:11','巡山',3000,'大王叫我来巡山');
修改表
提示:ALTER语句为修改表结构的语句,不直接操作某一行的记录
ALTER TABLE `emp`
ADD image VARCHAR(32) NOT NULL DEFAULT '' AFTER RESUME
DESC emp
ALTER TABLE emp
MODIFY job VARCHAR(60) NOT NULL DEFAULT ''
ALTER TABLE emp
DROP sex
RENAME TABLE emp TO employee
ALTER TABLE employee CHARACTER SET utf8
ALTER TABLE employee
CHANGE `name` user_name VARCHAR(32) NOT NULL DEFAULT ''
DESC employee
数据库 CRUD语句
C[create]R[read]U[update]D[delete]语句对应:
- Insert语句 (添加数据)
- Update语句 (更新数据)
- Delete语句 (删除数据)
- Select语句 (查找数据)
Insert语句
使用 INSERT 语句向表中插入数据
CREATE TABLE `goods`(id INT,goods_name VARCHAR(10),price DOUBLE);
INSERT INTO `goods`(id,goods_name,price)
VALUES(10,'华为手机',2000);
SELECT * FROM goods;
DESC employee;
INSERT INTO employee VALUES(200,'大王','1999-10-10','2000-11-11 11:11:11','管理',10000000,'代我去巡山','鍪啊');
SELECT * FROM employee;
细节说明:
DESC goods;
SELECT * FROM goods;
INSERT INTO goods (id,goods_name,price)
VALUES('韩顺平','小米手机',2000);
INSERT INTO goods (id,goods_name,price)
VALUES('韩顺平','小米手机小米手机小米手机小米手机',2000);
INSERT INTO goods(id,goods_name,price)
VALUES('vivo手机',40,3000);
INSERT INTO goods(goods_name,id,price)
VALUES('vivo手机',40,3000);
INSERT INTO goods(id,goods_name,price)
VALUES(40,vivo手机,3000);
INSERT INTO goods(id,goods_name,price)
VALUES('50','vivo手机',3000);
INSERT INTO goods(id,goods_name,price)
VALUES(40,'vovo手机',null);
INSERT INTO `goods` (id,goods_name,price)
VALUES(50,'三星手机',2000),(60,'海尔手机',3000);
INSERT INTO goods VALUES(70,'IBM手机',5000);
ALTER TABLE goods
MODIFY price DOUBLE NULL DEFAULT 500;
INSERT INTO goods(id,goods_name)
VALUES(80,'格力手机');
Update语句
使用 update 语句修改表中数据
SELECT * FROM employee;
UPDATE employee SET salary =5000;
UPDATE employee SET salary =3000 WHERE user_name='小妖怪';
UPDATE employee SET salary =salary+1000 WHERE user_name='大王';
UPDATE employee SET salary=salary+1000,job='出主意'
WHERE user_name='大王';
细节说明:
Delete语句
使用 delete 语句删除表中数据
DELETE FROM employee
WHERE user_name='大王';
INSERT INTO employee VALUES(200,'大王','1999-10-10','2000-11-11 11:11:11','管理',10000000,'代我去巡山','鍪啊');
SELECT * FROM employee;
DELETE FROM employee;
DROP TABLE employee;
细节说明:
Select语句
create table student(
id int not null default 1,
name varchar(20) not null default '',
chinese float not null default 0.0,
english float not null default 0.0,
math float not null default 0.0
);
insert into student(id,name,chinese,english,math) values(1,'韩顺平',89,78,90);
insert into student(id,name,chinese,english,math) values(2,'张飞',67,98,56);
insert into student(id,name,chinese,english,math) values(3,'宋江',87,78,77);
insert into student(id,name,chinese,english,math) values(4,'关羽',88,98,90);
insert into student(id,name,chinese,english,math) values(5,'赵云',82,84,67);
insert into student(id,name,chinese,english,math) values(6,'欧阳锋',55,85,45);
insert into student(id,name,chinese,english,math) values(7,'黄蓉',75,65,30);
DELETE FROM student
WHERE id=5;
SELECT * FROM student;
SELECT `name`,english FROM student;
SELECT DISTINCT * FROM student;
SELECT DISTINCT math FROM student;
使用表达式和AS语句
SELECT * FROM student;
SELECT `name`,(chinese+english+math) FROM student;
SELECT `name`,(chinese+english+math+10) FROM student;
SELECT `name` AS '名字',(chinese+english+math+10) AS total_score FROM student;
where过滤查询
在 where 子句中经常使用的运算符
练习:
SELECT * FROM student;
SELECT `name`,(chinese+math+english) `sum`
FROM student;
SELECT * FROM student WHERE `name`='赵云';
SELECT * FROM student WHERE english>90;
SELECT * FROM student
WHERE (chinese+math+english)>200;
SELECT * FROM student WHERE math>60 AND id>4;
SELECT * FROM student WHERE english>chinese;
SELECT * FROM student
WHERE (chinese+math+english)>200 AND math<chinese AND `name` LIKE '赵%';
SELECT * FROM student WHERE english BETWEEN 80 AND 90;
SELECT * FROM student WHERE math=89 OR math=90 OR math=91;
SELECT * FROM student WHERE math IN (89,90,91);
SELECT * FROM student WHERE `name` LIKE '赵%';
order by 子句
SELECT * FROM student;
INSERT INTO student VALUES(8,'韩琛',45,65,99);
SELECT * FROM student ORDER BY math;
SELECT * FROM student ORDER BY math DESC;
SELECT `name`,(chinese+math+english) total_score FROM student ORDER BY (chinese+math+english) DESC;
SELECT *, (chinese+math+english) total_score FROM student WHERE `name` LIKE '韩%' ORDER BY total_score;
函数
合计/聚合/统计函数
SELECT COUNT(*) FROM student;
SELECT COUNT(*) FROM student WHERE math>90;
SELECT COUNT(*) FROM student WHERE (chinese+math+english>250);
CREATE TABLE t15(
`name` VARCHAR(20));
INSERT INTO t15 VALUES('tom');
INSERT INTO t15 VALUES('jack');
INSERT INTO t15 VALUES('mary');
INSERT INTO t15 VALUES(NULL);
SELECT COUNT(*) FROM t15;
SELECT COUNT(`name`) FROM t15;
SELECT SUM(math) FROM student;
SELECT SUM(math),SUM(chinese),SUM(english) FROM student;
SELECT SUM(chinese+math+english) FROM student;
SELECT SUM(chinese)/COUNT(*) FROM student;
SELECT AVG(chinese) FROM student;
SELECT AVG(chinese+math+english) FROM student;
SELECT MAX(chinese+math+english),MIN(chinese+math+english) FROM student;
配合 group by ,having 子句使用
CREATE TABLE dept(
deptno MEDIUMINT UNSIGNED NOT NULL DEFAULT 0,
dname VARCHAR(20) NOT NULL DEFAULT "",
loc VARCHAR(13) NOT NULL DEFAULT ""
);
INSERT INTO dept VALUES(10, 'ACCOUNTING', 'NEW YORK'), (20, 'RESEARCH', 'DALLAS'), (30, 'SALES', 'CHICAGO'), (40, 'OPERATIONS', 'BOSTON');
CREATE TABLE emp
(empno MEDIUMINT UNSIGNED NOT NULL DEFAULT 0,
ename VARCHAR(20) NOT NULL DEFAULT "",
job VARCHAR(9) NOT NULL DEFAULT "",
mgr MEDIUMINT UNSIGNED ,
hiredate DATE NOT NULL,
sal DECIMAL(7,2) NOT NULL,
comm DECIMAL(7,2) ,
deptno MEDIUMINT UNSIGNED NOT NULL DEFAULT 0
);
INSERT INTO emp VALUES(7369, 'SMITH', 'CLERK', 7902, '1990-12-17', 800.00,NULL , 20),
(7499, 'ALLEN', 'SALESMAN', 7698, '1991-2-20', 1600.00, 300.00, 30),
(7521, 'WARD', 'SALESMAN', 7698, '1991-2-22', 1250.00, 500.00, 30),
(7566, 'JONES', 'MANAGER', 7839, '1991-4-2', 2975.00,NULL,20),
(7654, 'MARTIN', 'SALESMAN', 7698, '1991-9-28',1250.00,1400.00,30),
(7698, 'BLAKE','MANAGER', 7839,'1991-5-1', 2850.00,NULL,30),
(7782, 'CLARK','MANAGER', 7839, '1991-6-9',2450.00,NULL,10),
(7788, 'SCOTT','ANALYST',7566, '1997-4-19',3000.00,NULL,20),
(7839, 'KING','PRESIDENT',NULL,'1991-11-17',5000.00,NULL,10),
(7844, 'TURNER', 'SALESMAN',7698, '1991-9-8', 1500.00, NULL,30),
(7900, 'JAMES','CLERK',7698, '1991-12-3',950.00,NULL,30),
(7902, 'FORD', 'ANALYST',7566,'1991-12-3',3000.00, NULL,20),
(7934,'MILLER','CLERK',7782,'1992-1-23', 1300.00, NULL,10);
CREATE TABLE salgrade
(
grade MEDIUMINT UNSIGNED NOT NULL DEFAULT 0,
losal DECIMAL(17,2) NOT NULL,
hisal DECIMAL(17,2) NOT NULL
);
INSERT INTO salgrade VALUES (1,700,1200);
INSERT INTO salgrade VALUES (2,1201,1400);
INSERT INTO salgrade VALUES (3,1401,2000);
INSERT INTO salgrade VALUES (4,2001,3000);
INSERT INTO salgrade VALUES (5,3001,9999);
SELECT * FROM dept;
SELECT * FROM emp;
SELECT * FROM salgrade;
SELECT AVG(sal),MAX(sal),deptno FROM emp GROUP BY deptno;
SELECT sal FROM emp GROUP BY deptno;
SELECT AVG(sal),MIN(sal),deptno,job FROM emp GROUP BY deptno,job;
SELECT deptno,AVG(sal) AS `avg` FROM emp GROUP BY deptno HAVING `avg` <=2000 ;
字符串相关函数
SELECT * FROM emp;
SELECT CHARSET(`ename`) FROM emp;
SELECT CONCAT(ename,'的工作是',job) FROM emp;
SELECT INSTR('zxkedu','edu') FROM DUAL;
SELECT UCASE(ename) FROM emp;
SELECT LCASE(ename) FROM emp;
SELECT LEFT(ename,2) FROM emp;
SELECT RIGHT(ename,2) FROM emp;
SELECT LENGTH(ename) FROM emp;
SELECT ename,REPLACE(job,'MANAGER','经理') FROM emp;
SELECT STRCMP('zk','zxk') FROM DUAL;
SELECT SUBSTRING(ename,2) FROM emp;
SELECT LTRIM(' zxk') FROM DUAL;
SELECT RTRIM('zxk ') FROM DUAL;
SELECT TRIM(' zxk ') FROM DUAL;
SELECT CONCAT(LCASE(LEFT(ename,1) ),SUBSTRING(ename,2) ) newname1 FROM emp;
SELECT CONCAT(LCASE(SUBSTRING(ename,1,1) ),SUBSTRING(ename,2) ) newname2 FROM emp;
数学相关函数
SELECT ABS(-15) FROM DUAL;
SELECT BIN(10) FROM DUAL;
SELECT CEILING(1.1) FROM DUAL;
SELECT CONV(16,16,10) FROM DUAL;
SELECT FLOOR(-1.1) FROM DUAL;
SELECT FORMAT(78.125458,2) FROM DUAL;
SELECT CONV(32,10,16) FROM DUAL;
SELECT LEAST(0,1,-10,4) FROM DUAL;
SELECT MOD(10,3) FROM DUAL;
SELECT RAND() FROM DUAL;
SELECT RAND(3) FROM DUAL;
SELECT CURRENT_TIMESTAMP() FROM DUAL;
时间日期相关函数
SELECT CURRENT_DATE() FROM DUAL;
SELECT CURRENT_TIME() FROM DUAL;
SELECT CURRENT_TIMESTAMP() FROM DUAL;
CREATE TABLE mes(
id INT ,
content VARCHAR(30),
send_time DATETIME);
INSERT INTO mes
VALUES(1, '北京新闻', CURRENT_TIMESTAMP());
INSERT INTO mes VALUES(2, '上海新闻', NOW());
INSERT INTO mes VALUES(3, '广州新闻', NOW());
UPDATE mes SET send_time=NOW() WHERE id=2;
SELECT * FROM mes ORDER BY send_time;
SELECT * FROM mes;
SELECT NOW() FROM DUAL;
SELECT id,content,DATE(send_time) FROM mes;
SELECT * FROM mes WHERE send_time>DATE_SUB(NOW(),INTERVAL 10 MINUTE);
SELECT * FROM mes WHERE DATE_ADD(send_time,INTERVAL 10 MINUTE)>NOW();
SELECT DATEDIFF('2011-11-11','1990-1-1') FROM DUAL;
SELECT DATEDIFF(CURRENT_DATE,'1998-07-29') FROM DUAL;
SELECT DATE_ADD('1998-07-29',INTERVAL 80 YEAR) FROM DUAL;
SELECT DATEDIFF('2078-07-29',NOW()) FROM DUAL;
SELECT DATEDIFF(DATE_ADD('1998-07-29',INTERVAL 80 YEAR),NOW()) FROM DUAL;
SELECT TIMEDIFF('10:11:11','04:10:10') FROM DUAL;
SELECT YEAR(NOW()) FROM DUAL;
SELECT unix_timestamp() FROM DUAL;
SELECT FROM_UNIXTIME(1644769696,'%Y-%m-%d') FROM DUAL;
SELECT FROM_UNIXTIME(1644769696,'%Y-%m-%d %H-%i-%s') FROM DUAL;
SELECT FROM_UNIXTIME(unix_timestamp()) FROM DUAL;
SELECT * FROM mysql.user \G
加密和系统函数
SELECT USER() FROM DUAL;
SELECT DATABASE();
SELECT MD5('root') FROM DUAL;
SELECT LENGTH(MD5('root')) FROM DUAL;
CREATE TABLE hsp_user
(id INT ,
`name` VARCHAR(32) NOT NULL DEFAULT '',
pwd CHAR(32) NOT NULL DEFAULT '');
INSERT INTO hsp_user
VALUES(100, '韩顺平', MD5('hsp'));
SELECT * FROM hsp_user;
SELECT * FROM hsp_user
WHERE `name`='韩顺平' AND pwd = MD5('hsp');
SELECT PASSWORD('root') FROM DUAL;
SELECT * FROM mysql.user;
流程控制函数
SELECT * FROM emp;
SELECT IF(TRUE, '北京', '上海') FROM DUAL;
SELECT IFNULL( NULL, '韩顺平教育') FROM DUAL;
SELECT CASE
WHEN TRUE THEN 'jack'
WHEN FALSE THEN 'tom'
ELSE 'mary' END
SELECT ename,job,IF(comm IS NULL,0.0,comm) FROM emp;
SELECT ename,job,IFNULL(comm,0.0) FROM emp;
SELECT ename,job,CASE
WHEN comm IS NULL THEN 0.0
ELSE comm END
FROM emp;
SELECT ename,(SELECT CASE
WHEN job ='CLERK' THEN '职员'
WHEN job ='MANAGER' THEN '经理'
WHEN job ='SALESMAN' THEN '销售人员'
ELSE job END)AS 'job'
FROM emp;
mysql表查询–加强
练习:
DESC emp;
SELECT * FROM emp WHERE hiredate>'1992-01-01';
SELECT ename,sal FROM emp WHERE ename LIKE 's%';
SELECT ename,sal FROM emp WHERE ename LIKE '__O%';
SELECT * FROM emp WHERE mgr IS NULL;
DESC emp;
SELECT * FROM emp ORDER BY sal;
SELECT * FROM emp ORDER BY deptno ASC ,sal DESC;
SELECT * FROM emp GROUP BY deptno ,sal ;
分页查询
SELECT * FROM emp
ORDER BY empno
LIMIT 0, 3;
SELECT * FROM emp
ORDER BY empno
LIMIT 3, 3;
SELECT * FROM emp
ORDER BY empno
LIMIT 6, 3;
SELECT * FROM emp;
SELECT * FROM emp ORDER BY empno DESC LIMIT 10,5;
SELECT * FROM emp
ORDER BY empno
LIMIT 每页显示记录数 * (第几页-1) , 每页显示记录数
分组函数和分组子句 group by
SELECT * FROM emp;
SELECT COUNT(*),AVG(sal) ,job FROM emp GROUP BY job;
SELECT COUNT(*),COUNT(comm) FROM emp;
SELECT COUNT(IF(comm IS NULL,1,NULL)) FROM emp;
SELECT COUNT(*)-COUNT(comm) FROM emp;
SELECT COUNT(DISTINCT mgr) FROM emp;
SELECT MAX(sal)-MIN(sal) FROM emp;
SELECT AVG(sal) sal_avg FROM emp GROUP BY deptno HAVING sal_avg>1000 ORDER BY sal_avg DESC LIMIT 0,2;
数据分组等的总结
-
GROUP BY的使用顺序:WHERE 比较运算/逻辑运算=0/1 GROUP BY 字段1,字段2 HAVING 比较运算/逻辑运算 分组前过滤+分组+分组后过滤 按每个字段1中的字段2查询:GROUP BY 字段1,字段2 注意:数据分组的正确语法顺序:WHERE+GROUP BY+HAVING+ORDER BY+LIMIT -
ORDER BY的排序顺序同GROUP BY,按字段1的升序基础上字段2降序查询:ORDER BY 字段1 ASC,字段2 DESC -
GROUP BY 和ORDER BY的分组区别: 从结果上看:分组结果会将 分组后 同组且不再分 的行聚合为一行, 排序结果 分组后 则不会 -
日期时间类:
多表查询
SELECT * FROM dept;
SELECT * FROM salgrade;
SELECT * FROM emp;
SELECT ename ,sal,dname,emp.deptno FROM emp , dept WHERE emp.deptno=dept.deptno;
SELECT ename ,sal,dname,emp.deptno FROM emp , dept WHERE emp.deptno=dept.deptno AND emp.deptno=10;
SELECT ename,sal,grade FROM emp,salgrade WHERE sal BETWEEN losal AND hisal;
自连接
SELECT * FROM emp;
SELECT emp.ename emp,boss.ename boss FROM emp,emp AS boss WHERE emp.mgr=boss.empno;
子查询(嵌套查询)
单行子查询
单行子查询是指只返回一行数据的子查询语句
多行子查询(in)
多行子查询指返回多行数据的子查询 使用关键字 in
SELECT deptno FROM emp WHERE ename='SMITH';
SELECT *
FROM emp
WHERE deptno=(
SELECT deptno
FROM emp
WHERE ename='SMITH'
);
SELECT DISTINCT job
FROM emp
WHERE deptno =10;
SELECT ename,job,sal,deptno
FROM emp
WHERE job in(
SELECT DISTINCT job
FROM emp
WHERE deptno =10
) AND deptno <>10;
SELECT goods_id,cat_id,goods_name,shop_price FROM ecs_goods;
SELECT cat_id,MAX(shop_price) AS hi_price
FROM ecs_goods
GROUP BY cat_id;
SELECT goods_id,ecs_goods.cat_id,goods_name,shop_price
FROM(
SELECT cat_id,MAX(shop_price) AS hi_price
FROM ecs_goods
GROUP BY cat_id
) temp,ecs_goods
WHERE temp.cat_id=ecs_goods.cat_id
AND hi_price=shop_price;
all&any
SELECT ename,sal,deptno
FROM emp
WHERE sal>ALL(
SELECT sal FROM emp WHERE deptno=30
);
SELECT ename,sal,deptno
FROM emp
WHERE sal>(
SELECT MAX(sal) FROM emp WHERE deptno=30
);
SELECT ename,sal,deptno
FROM emp
WHERE sal>ANY(
SELECT sal FROM emp WHERE deptno=30
);
SELECT ename,sal,deptno
FROM emp
WHERE sal>(
SELECT MIN(sal) FROM emp WHERE deptno=30
);
多列子查询
SELECT * FROM emp;
SELECT deptno ,job FROM emp WHERE ename='ALLEN';
SELECT *
FROM emp
WHERE (deptno,job) =(
SELECT deptno ,job
FROM emp
WHERE ename='ALLEN'
)AND ename <>'ALLEN';
SELECT * FROM student;
SELECT chinese,math,english FROM student WHERE `name` ='宋江';
SELECT *
FROM student
WHERE (chinese,math,english)=(
SELECT chinese,math,english
FROM student
WHERE `name` ='宋江'
)AND `name` <>'宋江';
from 子句中使用子查询
SELECT deptno,AVG(sal) FROM emp GROUP BY deptno;
SELECT ename,sal,sal_avg,emp.deptno
FROM emp,(
SELECT deptno,AVG(sal) AS sal_avg
FROM emp
GROUP BY deptno
) temp
WHERE emp.deptno=temp.deptno
AND sal>sal_avg;
SELECT deptno,MAX(sal) FROM emp GROUP BY deptno;
SELECT * FROM emp WHERE (deptno,sal) IN (SELECT deptno,MAX(sal) FROM emp GROUP BY deptno);
SELECT ename,sal,sal_max,emp.deptno
FROM emp,(
SELECT deptno,MAX(sal) AS sal_max
FROM emp
GROUP BY deptno
) temp
WHERE emp.deptno=temp.deptno
AND sal=sal_max;
SELECT * FROM dept;
SELECT deptno,COUNT(*) FROM emp GROUP BY deptno;
SELECT dept.*,`count`
FROM dept,(
SELECT deptno,COUNT(*) `count`
FROM emp
GROUP BY deptno
) temp
WHERE dept.deptno=temp.deptno;
表复制
自我复制数据(蠕虫复制)
CREATE TABLE mytab_01
(id INT ,
`name` VARCHAR(32),
sal DOUBLE ,
job VARCHAR(32),
deptno INT );
DESC mytab_01;
SELECT * FROM mytab_01;
SELECT * FROM emp;
INSERT INTO mytab_01
(id,`name`,sal,job,deptno)
SELECT empno,ename,sal,job,deptno FROM emp;
INSERT INTO mytab_01
SELECT * FROM mytab_01;
SELECT COUNT(*) FROM mytab_01;
SELECT DISTINCT * FROM mytab_01;
CREATE TABLE tmp like mytab_01;
SELECT * FROM tmp;
INSERT INTO tmp
SELECT DISTINCT * FROM mytab_01;
DELETE FROM mytab_01;
INSERT INTO mytab_01
SELECT * FROM tmp;
DROP TABLE tmp;
合并查询
SELECT ename,sal,job FROM emp WHERE sal>2500;
SELECT ename,sal,job FROM emp WHERE job='MANAGER'
SELECT ename,sal,job FROM emp WHERE sal>2500
UNION ALL
SELECT ename,sal,job FROM emp WHERE job='MANAGER'
SELECT ename,sal,job FROM emp WHERE sal>2500
UNION
SELECT ename,sal,job FROM emp WHERE job='MANAGER'
外连接
SELECT * FROM dept;
SELECT dname,ename,job,dept.deptno
FROM emp , dept
WHERE emp.deptno=dept.deptno
ORDER BY deptno;
SELECT dname,ename,job,dept.deptno
FROM emp RIGHT JOIN dept
ON emp.deptno=dept.deptno
ORDER BY deptno;
SELECT dname,ename,job,dept.deptno
FROM dept LEFT JOIN emp
ON emp.deptno=dept.deptno
ORDER BY deptno;
约束
主键
CREATE TABLE t17
(id INT PRIMARY KEY,
`name` VARCHAR(32),
email VARCHAR(32));
INSERT INTO t17
VALUES(1,'jack','jack@sohu.com');
INSERT INTO t17
VALUES(2,'mary','mary@sohu.com');
INSERT INTO t17
VALUES(1,'zxk','zxk@sohu.com');
SELECT * FROM t17;
INSERT INTO t17
VALUES(NULL, 'hsp', 'hsp@sohu.com');
CREATE TABLE t18
(id INT PRIMARY KEY,
`name` VARCHAR(32), PRIMARY KEY
email VARCHAR(32));
CREATE TABLE t18
(id INT ,
`name` VARCHAR(32),
email VARCHAR(32),
PRIMARY KEY(id,`name`)
);
INSERT INTO t18
VALUES(1, 'tom', 'tom@sohu.com');
INSERT INTO t18
VALUES(1, 'jack', 'jack@sohu.com');
INSERT INTO t18
VALUES(1, 'tom', 'xx@sohu.com');
SELECT * FROM t18;
CREATE TABLE t19
(id INT ,
`name` VARCHAR(32) PRIMARY KEY,
email VARCHAR(32)
);
CREATE TABLE t20
(id INT,
`name` VARCHAR(32),
email VARCHAR(32),
PRIMARY KEY(`name`)
);
DESC t20
DESC t18
非空
唯一
CREATE TABLE t21
(id INT UNIQUE,
`name` VARCHAR(32),
emain VARCHAR(32)
);
INSERT INTO t21
VALUES(1,'jack','jack@sohu.com');
INSERT INTO t21
VALUES(1,'mary','mary@sohu.com');
INSERT INTO t21
VALUES(NULL,'hsp','hsp@sohu.com');
SELECT * FROM t21;
CREATE TABLE t22
(id INT UNIQUE NOT NULL,
`name` VARCHAR(32) UNIQUE,
email VARCHAR(32)
);
DESC t22;
外键
CREATE TABLE my_class
(id INT UNIQUE,
nam VARCHAR(32) NOT NULL DEFAULT ''
);
INSERT INTO my_class
VALUES(100,'java'),(200,'web');
DESC my_class;
SELECT * FROM my_class;
CREATE TABLE my_stu
(id INT ,
`name` VARCHAR(32),
class_id INT,
FOREIGN KEY (class_id) REFERENCES my_class(id));
INSERT INTO my_stu
VALUES(1,'tom',100);
INSERT INTO my_stu
VALUES(2,'jack',200);
INSERT INTO my_stu
VALUES(1,'tom',100);
INSERT INTO my_stu
VALUES(4,'mary',300);
INSERT INTO my_stu
VALUES(5,'zxk',NULL);
SELECT * FROM my_stu;
DELETE FROM my_class WHERE id=100;
check
CREATE TABLE t23(
id INT PRIMARY KEY,
`name` VARCHAR(32),
sex CHAR(6) CHECK (sex IN('man','woman')),
sal DOUBLE CHECK (sal>1000 AND sal<2000)
);
INSERT INTO t23
VALUES(1,'hsp','mid',1);
SELECT * FROM t23;
练习
CREATE TABLE goods
(goods_id INT PRIMARY KEY,
goods_name VARCHAR(64) NOT NULL DEFAULT '',
unitprice DECIMAL(10,2) NOT NULL DEFAULT 0 CHECK (unitprice>=1.0 AND unitprice<=9999.99),
category INT NOT NULL DEFAULT 0,
provider VARCHAR(64) NOT NULL DEFAULT ''
);
CREATE TABLE customer
(customer_id CHAR(8) PRIMARY KEY,
`name` VARCHAR(10) NOT NULL DEFAULT '',
address VARCHAR(64) NOT NULL DEFAULT '',
email VARCHAR(64) UNIQUE NOT NULL DEFAULT '',
sex ENUM('男','女') NOT NULL,
card_Id CHAR(18)
);
CREATE TABLE purchase
(order_id INT UNSIGNED PRIMARY KEY,
customer_id CHAR(8) NOT NULL DEFAULT '',
goods_id INT NOT NULL DEFAULT 0,
nums INT NOT NULL DEFAULT 0,
FOREIGN KEY (customer_id) REFERENCES customer(customer_id),
FOREIGN KEY (goods_id) REFERENCES goods(goods_id)
);
自增长
CREATE TABLE t24
(id INT PRIMARY KEY AUTO_INCREMENT,
email VARCHAR(32) NOT NULL DEFAULT '',
`name` VARCHAR(32) NOT NULL DEFAULT ''
);
DESC t24;
INSERT INTO t24(id,email,`name`)
VALUES(NULL,'hsp.com','hsp');
INSERT INTO t24(email,`name`)
VALUES('sohu.com','sohu');
INSERT INTO t24
VALUES(NULL,'zxk.com','zxk');
SELECT * FROM t24;
INSERT INTO t24
VALUES(666,'zxk.com','zxk');
INSERT INTO t24(email,`name`)
VALUES('sohu.com','sohu');
CREATE TABLE t25
(id INT PRIMARY KEY AUTO_INCREMENT,
email VARCHAR(32) NOT NULL DEFAULT '',
`name` VARCHAR(32) NOT NULL DEFAULT ''
);
ALTER TABLE t25 AUTO_INCREMENT=100;
INSERT INTO t25(id,email,`name`)
VALUES(NULL,'hsp.com','hsp');
SELECT * FROM t25;
索引
入门
CREATE TABLE dept(
deptno MEDIUMINT UNSIGNED NOT NULL DEFAULT 0,
dname VARCHAR(20) NOT NULL DEFAULT "",
loc VARCHAR(13) NOT NULL DEFAULT ""
) ;
CREATE TABLE emp
(empno MEDIUMINT UNSIGNED NOT NULL DEFAULT 0,
ename VARCHAR(20) NOT NULL DEFAULT "",
job VARCHAR(9) NOT NULL DEFAULT "",
mgr MEDIUMINT UNSIGNED NOT NULL DEFAULT 0,
hiredate DATE NOT NULL,
sal DECIMAL(7,2) NOT NULL,
comm DECIMAL(7,2) NOT NULL,
deptno MEDIUMINT UNSIGNED NOT NULL DEFAULT 0
) ;
CREATE TABLE salgrade
(
grade MEDIUMINT UNSIGNED NOT NULL DEFAULT 0,
losal DECIMAL(17,2) NOT NULL,
hisal DECIMAL(17,2) NOT NULL
);
INSERT INTO salgrade VALUES (1,700,1200);
INSERT INTO salgrade VALUES (2,1201,1400);
INSERT INTO salgrade VALUES (3,1401,2000);
INSERT INTO salgrade VALUES (4,2001,3000);
INSERT INTO salgrade VALUES (5,3001,9999);
delimiter $$
create function rand_string(n INT)
returns varchar(255)
begin
declare chars_str varchar(100) default
'abcdefghijklmnopqrstuvwxyzABCDEFJHIJKLMNOPQRSTUVWXYZ';
declare return_str varchar(255) default '';
declare i int default 0;
while i < n do
set return_str =concat(return_str,substring(chars_str,floor(1+rand()*52),1));
set i = i + 1;
end while;
return return_str;
end $$
create function rand_num( )
returns int(5)
begin
declare i int default 0;
set i = floor(10+rand()*500);
return i;
end $$
create procedure insert_emp(in start int(10),in max_num int(10))
begin
declare i int default 0;
set autocommit = 0;
repeat
set i = i + 1;
insert into emp values ((start+i) ,rand_string(6),'SALESMAN',0001,curdate(),2000,400,rand_num());
until i = max_num
end repeat;
commit;
end $$
call insert_emp(100001,8000000)$$
delimiter ;
SELECT COUNT(*) FROM emp;
SELECT * FROM emp WHERE empno=1234567;
CREATE INDEX empno_index ON emp(empno);
SELECT * FROM emp WHERE ename='PjDlwy';
CREATE INDEX ename_index ON emp(ename);
原理
类型
使用
CREATE TABLE t25
(id INT,
ic INT,
`name` VARCHAR(32));
DESC t25;
SHOW INDEXES FROM t25;
CREATE UNIQUE INDEX ic_index ON t25(ic);
ALTER TABLE t25
ADD UNIQUE INDEX (ic);
CREATE INDEX name_index ON t25(`name`);
ALTER TABLE t25
ADD INDEX (`name`);
ALTER TABLE t25
ADD PRIMARY KEY (id);
DROP INDEX ic_index ON t25;
ALTER TABLE t25 DROP INDEX name_index;
ALTER TABLE t25 DROP PRIMARY KEY;
SHOW INDEX FROM t25;
SHOW INDEXES FROM t25;
SHOW KEY FROM t25;
DESC t25;
使用小结
事务
定义
CREATE TABLE t27
(id INT ,
`name` VARCHAR(32));
START TRANSACTION;
SAVEPOINT a;
INSERT INTO t27
VALUES(100,'jack');
SAVEPOINT b;
INSERT INTO t27
VALUES(200,'mary');
SELECT * FROM t27;
ROLLBACK TO b;
ROLLBACK TO a;
ROLLBACK;
COMMIT;
回退事务
提交事务
细节
SELECT * FROM t27;
INSERT INTO t27
VALUES(300,'zxk');
START TRANSACTION;
INSERT INTO t27
VALUES(400,'smith'),(500,'hsp');
ROLLBACK;
COMMIT;
事务隔离级别
案例:
设置事务隔离级别
SELECT @@tx_isolation;
SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
CREATE TABLE `account`(
id INT,
`name` VARCHAR(32),
money INT);
SELECT @@tx_isolation
SELECT @@global.tx_isolation
SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED
SET GLOBAL TRANSACTION ISOLATION LEVEL [你设置的级别]
transaction-isolation=READ-UNCOMMITTED
事务 ACID
事务的 acid 特性
表类型和存储引擎
主要的存储引擎/表类型特点
细节说明
使用案例
SHOW ENGINES;
CREATE TABLE t28
(id INT,
`name` VARCHAR(32)) ENGINE MYISAM;
START TRANSACTION;
SAVEPOINT a;
INSERT INTO t28 VALUES(1,'jack');
SELECT * FROM t28;
ROLLBACK TO a;
CREATE TABLE t29
(id INT,
`name` VARCHAR(32)) ENGINE MEMORY;
DESC t29;
INSERT INTO t29 VALUES(1,'tom'),(2,'mary'),(3,'scott');
SELECT * FROM t29;
ALTER TABLE t29 ENGINE=INNODB;
如何选择
修改存储引擎
视图
概念
基本使用
案例
CREATE VIEW emp_view01
AS
SELECT empno,ename,job,deptno FROM emp;
DESC emp_view01;
SELECT * FROM emp_view01;
SELECT empno,job FROM emp_view01;
SHOW CREATE VIEW emp_view01;
DROP VIEW emp_view01;
UPDATE emp_view01 SET job='MANAGER' WHERE empno=7369;
SELECT * FROM emp;
SELECT * FROM emp_view01;
UPDATE emp SET job='SALESMAN' WHERE empno=7369;
DESC emp_view01;
CREATE VIEW emp_view02
AS
SELECT empno,ename FROM emp_view01;
SELECT * FROM emp_view02;
视图细节讨论
视图最佳实践
练习
SELECT * FROM emp,dept,salgrade;
CREATE VIEW emp_view03
AS
SELECT empno,ename,dname,grade
FROM emp,dept,salgrade
WHERE emp.deptno=dept.deptno
AND (sal BETWEEN losal AND hisal);
DROP VIEW emp_view03;
DESC emp_view03;
SELECT * FROM emp_view03;
管理
创建用户
删除用户
用户修改密码
权限
给用户授权
回收用户授权
权限生效指令
练习
SELECT * FROM `user`;
SELECT PASSWORD('123456') FROM DUAL;
*6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9
CREATE USER 'zxk'@'localhost' IDENTIFIED BY '123';
CREATE DATABASE testdb;
CREATE TABLE news
(id INT,
content VARCHAR(32));
INSERT INTO news VALUES(100,'北京新闻');
GRANT SELECT,INSERT ON testdb.news TO 'zxk'@'localhost' ;
GRANT UPDATE ON testdb.news TO 'zxk'@'localhost' ;
SET PASSWORD FOR 'zxk'@'localhost'=PASSWORD('abc');
REVOKE SELECT,INSERT,UPDATE ON testdb.news FROM 'zxk'@'localhost';
REVOKE ALL ON testdb.news FROM 'zxk'@'localhost';
DROP USER 'zxk'@'localhost';
细节说明
CREATE USER jack;
SELECT * FROM `user`;
SELECT `host`,`user` FROM mysql.user;
CREATE USER 'mary'@'192.168.1.%';
DROP USER jack;
DROP USER 'mary'@'192.168.1.%';
|