一、SQL语句类型
1、DDL:数据定义语言
通常用于定义数据库对像
常见的数据库对象
数据库,表,索引,视图,存储过程,存储函数,约束,触发器,事件调度器。
2、DML:数据操作语言
GRUD: insert,select,update,delete
3、DCL:数据控制语言
GRANT,REVOKE
4、事务:
start transaction 启动事务,commit 提交事务,rollback 滚回,save point 保存点。
二、DDL语句的应用
1、数据库的操作语句
1)创建:create database|schema [if not exists] dbname;
msyql> create datebase mytestdb;
character set= 定义字符集
collate 定义默认排序规则
2)删除:drop database|schema [if exists] dbname;
mysql> drop database hellodb;
3)修改:alter database|schema dbname
升级数据字典 -upgrade data dircttory name
2、表的相关操作语句
查看表的状态
mysql> show table status\G
1)存储引擎类型,又称作表的类型
MyISAM表不支持事务
tbname.MYD 存储数据,tbname.MYI 存储索引,tbname.frm 表的定义
InnoDB表支持事务
tbname.frm 表的定义
tbname.ibd 表空间用于存储数据和索
开启表空间的方法:setbal innodb_file_per_table=1
mysql> show session variables like 'innodb%'; mysql> set global innodb_file_per_table = 1;
2)表的选项
engine=engine_name 定义存储引擎
delay_key_write={0|1} 是否延迟键写入
tablespace tablespace_name 明确指定使用的表空间
auto_increment 自动增长值
data dirctory /path/to 明确数据字典保存路径
max rows=value 最多能存储的行数
3)创建表
方式一:create table tb_name (col1 defination,col2 defination,...);自定义表的参数属性
CREATE TABLE `students` ( `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, `name` char(30) NOT NULL, `age` tinyint(3) unsigned DEFAULT NULL, `gender` char(1) DEFAULT 'm', `course` varchar(50) NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8
方式二:create table tb_name [(defination)] select clause; 依据查询结果创建表
mysql> create table teststudents select name,age,gender from students;
方式三:create table tb_name like old_table_name; 依据老表创建表
mysql> create table newstudents like students;
4)删除表
drop table [if exists] tb_name;
mysql> drop table newstudents;
5)改表名
rename table tb_name to new_name;
mysql> rename table teststudents to students1;
6)修改表
查看如何修改表
mysql> help alter table
alter table tb_name add colfinaton [{frist|after col_name}];增加新字段
mysql> alter table students1 add `course` varchar(50) NOT NULL after gender;
alter table tb_name drop colname;删除某个字段
mysql> alter table students drop course;
alter table tb_name modify col defination [{frist|after col_name}];
修改某个字段的属性
alter table tb_name change old_col_name new_col_name column_defination [{frist|after col_name}];
修改某字段的名称,并指定其位置
mysql> alter table students change course `courses` varchar(50) NOT NULL;
alter teable tb_name rename to new_name;改表名
mysql> alter table students1 rename to newstudents;
三、DML语句的应用
增删查改:insert,delete,select,update
1、增,insert语句的使用
1)insert into tb_name [(col1,col2,...)] {value|values}();
mysql> insert into students (name,age,gender,courses) values ('zhang wuji',20,'M','Q Query OK, 1 row affected (0.06 sec)
插入数值数据,不需要引号;
字符数据,需要引号;
空值,null。
2)insert into tb_name set col_name=value,...;
mysql> insert into students set name='Yang xiao',age=45,gender='M',courses='Jiuyang Shengong'; Query OK, 1 row affected (0.10 sec) mysql> select * from students; +----+--------------+------+--------+-----------------------+ | id | name | age | gender | courses | +----+--------------+------+--------+-----------------------+ | 1 | Ling Huchong | 24 | M | Hamogong | | 2 | Huang Rong | 19 | F | Chilian Shenzhang | | 3 | Lu Wushuang | 18 | F | Jiuying Shengong | | 4 | Zhu Ziliu | 52 | M | Pixie Jianfa | | 5 | Chen Jialuo | 22 | M | Xianglong Shiba Zhang | | 6 | zhang wuji | 20 | M | Qiankun Daluoqi | | 7 | Yang xiao | 45 | M | Jiuyang Shengong | +----+--------------+------+--------+-----------------------+
3)insert into tb_name (col1,..) select clause;
mysql> insert into newstudents (name,age,gender,course) value ('Zhang Sanfeng',80,'M','Tai Ji'); Query OK, 1 row affected (0.05 sec) mysql> insert into students (name,age,gender,courses) select * from newstudents where name='Zhang Sanfeng'; Query OK, 1 row affected (0.08 sec) Records: 1 Duplicates: 0 Warnings: 0
4)replace into tb_name (col1,..)
替换操作,有�t替换,无则插入
2、删,delete语句的使用
delete from tb_name where vlaue;
mysql> delete from newstudents where name='Zhu Ziliu'; Query OK, 1 row affected (0.09 sec)
3、改,update语句的使用
update from tb_name col1,... where vlaue;
mysql> update newstudents set age=28 where name='Chen Jialuo'; Query OK, 1 row affected (0.05 sec) Rows matched: 1 Changed: 1 Warnings: 0
4、清空并重置表,效果比删要好
truncate table tb_name;
查看最后一次插入的数据的ID号
mysql> select last_insert_ID(); +------------------+ | last_insert_ID() | +------------------+ | 9 | +------------------+ 1 row in set (0.00 sec)
四、DML语句之查语句的使用
1、表的查询方式
全表查询和使用索引查询,表只要有一个索引,完成查询至少有两条路径。
2、查看所有字段信息
select * from tb_name;
mysql> select * from newstudents; +---------------+------+--------+---------+ | name | age | gender | courses | +---------------+------+--------+---------+ | Ling Huchong | 24 | M | | | Huang Rong | 19 | F | | | Lu Wushuang | 18 | F | | | Chen Jialuo | 28 | M | | | Zhang Sanfeng | 80 | M | Tai Ji | +---------------+------+--------+---------+ 5 rows in set (0.00 sec)
3、基于行与字段的查询
1)投影:select col1.col2 from tb_name;限定字段
mysql> select age=18 from newstudents; +--------+ | age=18 | +--------+ | 0 | | 0 | | 1 | | 0 | | 0 | +--------+ 5 rows in set (0.00 sec)
2)选择:select * from where clause;限定行
mysql> select * from newstudents where name='Huang Rong'; +------------+------+--------+---------+ | name | age | gender | courses | +------------+------+--------+---------+ | Huang Rong | 19 | F | | +------------+------+--------+---------+ 1 row in set (0.01 sec)
3)合并:select col1,col2 from tb_name where clause;即限定字段又限定行
mysql> select age from newstudents where name='Lu Wushuang'; +------+ | age | +------+ | 18 | +------+ 1 row in set (0.00 sec)
4、where子句
比较表达式+算术表达式
1)连续集合:between value1 and value2;
mysql> select * from students where age between 20 and 24; +----+--------------+------+--------+-----------------------+ | id | name | age | gender | courses | +----+--------------+------+--------+-----------------------+ | 1 | Ling Huchong | 24 | M | Hamogong | | 5 | Chen Jialuo | 22 | M | Xianglong Shiba Zhang | | 6 | zhang wuji | 20 | M | Qiankun Daluoqi | +----+--------------+------+--------+-----------------------+ 3 rows in set (0.00 sec)
2)离散集合:in (element1,element2,...);
mysql> select * from students where id in (2,3,4); +----+-------------+------+--------+-------------------+ | id | name | age | gender | courses | +----+-------------+------+--------+-------------------+ | 2 | Huang Rong | 19 | F | Chilian Shenzhang | | 3 | Lu Wushuang | 18 | F | Jiuying Shengong | | 4 | Zhu Ziliu | 52 | M | Pixie Jianfa | +----+-------------+------+--------+-------------------+ 3 rows in set (0.00 sec)
3)空集合与非空集合:is null;
is not null;
4)支持通配:like {%|_};
5)支持正则表达式:{relike|regexp} .,*,^,/>....
6)组合条件函数:and/&& 与,or/|| 或,not/!非,xor 异或
7) 算术表达式:>,<,>=,<=
mysql> select * from students where id<4 and gender='F'; +----+-------------+------+--------+-------------------+ | id | name | age | gender | courses | +----+-------------+------+--------+-------------------+ | 2 | Huang Rong | 19 | F | Chilian Shenzhang | | 3 | Lu Wushuang | 18 | F | Jiuying Shengong | +----+-------------+------+--------+-------------------+ 2 rows in set (0.00 sec)
8)聚合函数:max() 求最大值,min() 求最小值,avg() 求平均值,count() 计数器,sum() 求和。
求最大值
五、查询语句中的表相关查询
1、表相关的查询类型:
单表查询,联结查询(join),联合查询(union)
1)联结查询:多表查询,表与表之间通过某种关系(即相同的字段)组合起来完整地查询。
2)联合查询:将两个和两个以上的select语句查询结果联合起来。
2、表联结查询
1)交叉联结:两个表做笛卡尔乘积,产生结果在本地临时缓存下来。
2)内联结:又称为自然联结,让两张表对应的字段的值建立等值连接关系。
3)外联结:又分为左外联结和右外联结及全外联结
左外联结:两个或多个表以左边表为标准查询。
left_table left join right_table on condition;
右外联结:两个或多个表以右边表为标准查询。
right_table right join left_table on condition
4)自联结:自己与自己联结,同一张表定义两个别名
sometables as alias1 inter join sometable as alias2 on alias1 filed = alias2 filed
3、表的联合查询
select clause union select clause
4、表的子查询
1)用于where的子查询
select clause from tb_name where col...
用于比较表达式中的子查询;
用于exists中的子查询;
用于in中的子查询。
2)用于from中的子查询
select col,... from tb_name
注:mysql对于查询的优化很有限,尽量不要使用子查询。
多表查询实战案例
导入hellodb.sql,完成以下题目:
启用hellodb表
mysql> use hellodb; Database changed mysql> show tables; +-------------------+ | Tables_in_hellodb | +-------------------+ | classes | | coc | | courses | | mytest | | scores | | students | | teachers | | toc | +-------------------+ 8 rows in set (0.00 sec)
1、显示前5位同学的姓名、课程及成绩;
mysql> select Name,Course,Score from students,courses,scores where students.StuID=scores.StuID and scores.CourseID=courses.CourseID group by students.StuID limit 5; +-------------+----------------+-------+ | Name | Course | Score | +-------------+----------------+-------+ | Shi Zhongyu | Kuihua Baodian | 77 | | Shi Potian | Kuihua Baodian | 47 | | Xie Yanke | Kuihua Baodian | 88 | | Ding Dian | Daiyu Zanghua | 71 | | Yu Yutong | Hamo Gong | 39 | +-------------+----------------+-------+ 5 rows in set (0.06 sec)
2、显示其成绩高于80的同学的名称及课程;
mysql> select Name,Course,Score from students,courses,scores where students.StuID=scores.StuID and scores.CourseID=courses.CourseID and Score>=80 group by Name; +-------------+----------------+-------+ | Name | Course | Score | +-------------+----------------+-------+ | Ding Dian | Kuihua Baodian | 89 | | Lin Daiyu | Jinshe Jianfa | 93 | | Shi Potian | Daiyu Zanghua | 97 | | Shi Qing | Hamo Gong | 96 | | Shi Zhongyu | Weituo Zhang | 93 | | Xi Ren | Hamo Gong | 86 | | Xie Yanke | Kuihua Baodian | 88 | +-------------+----------------+-------+ 7 rows in set (0.00 sec)
3、求前8位同学每位同学自己两门课的平均成绩,并按降序排列;
mysql> select students.StuID,Name,avg(Score) from students,courses,scores where students.StuID=scores.StuID and scores.CourseID=courses.CourseID group by Name order by avg(Score) desc; +-------+-------------+------------+ | StuID | Name | AVG(Score) | +-------+-------------+------------+ | 6 | Shi Qing | 96.0000 | | 1 | Shi Zhongyu | 85.0000 | | 7 | Xi Ren | 84.5000 | | 3 | Xie Yanke | 81.5000 | | 4 | Ding Dian | 80.0000 | | 8 | Lin Daiyu | 75.0000 | | 2 | Shi Potian | 72.0000 | | 5 | Yu Yutong | 51.0000 | +-------+-------------+------------+ 8 rows in set (0.00 sec)
4、显示每门课程课程名称及学习的同学的个数;
mysql> select course,count(stuID) from students,courses,coc where students.ClassID=coc.ClassID and coc.CourseID=courses.CourseID group by course; +----------------+--------------+ | course | count(stuID) | +----------------+--------------+ | Dagou Bangfa | 4 | | Daiyu Zanghua | 8 | | Hamo Gong | 5 | | Jinshe Jianfa | 7 | | Kuihua Baodian | 11 | | Taiji Quan | 7 | | Weituo Zhang | 3 | +----------------+--------------+ 7 rows in set (0.05 sec)
六、mysql事务处理时锁机制
1、锁的概念:锁是保证并发性在临界区实现资源保护的一种机制。
2、锁的类型:表级锁,行级锁,页级锁。
MyISAM引擎只支持表级锁,而InnoDB引擎还支持行级锁。
3、加锁方式:
施加读锁,也称之为共享锁,则其他用户能读不能写;
施加写锁,也称之为独占锁,则其他用户既不能读更不能写;
4、加锁与解锁的方案:
施加显式锁 lock tables tb_name,... {read|write};
施加隐式锁 select [ for update | lock in share mode ];
释放锁 unlock tables;
七、事务
1、事务系统中的“ACID”
1)A/ 原子性:同一组的DML语句,要么都执行,要么都不执行;
2)C/ 一致性:数据从一种状态转换到另外一种状态总量不变;
3) I/ 隔离性:多个事务同时操作数据时可以互不干扰;
4)D/ 持久性:数据一旦提交不能丢失,未提交可以撤销,事务提交,则立即写入磁盘。
2、开启事务处理
start transaction
3、保存事务节点
savepoint point_name
4、滚回指定事务节点
rollback [ to somepoint ]
5、提交事务
commit
6、事务的隔离性,事务都是具有严格的隔离级别的,将两个或多个事务隔离开来进行处理。
1)读未提交:read uncommitted
读过后没有提交,能在不同的终端修改数据时,立即从别的终端读取,导致事务之间存在干扰。
2)读提交:read commited
读过后等待提交,不能再读取别的终端滚回去的数据,只能等待对方提交后才能读取。
3)可重读:repeatble read ,mysql服务默认的隔离级别
它确保同一事务的多个实例在并发读取数据时,会看到同样的数据行。但是会带来幻读效果。
4)可串行化:seriablizable
可串行化的事务只能一个接着一个的执行,不能并发执行,安全性最高,并解决了幻读。
本文出自 “丿Sky 灬ONE PEICE” 博客,转载请与作者联系!