本文对常用SQL语法进行总结,包括以下部分:
mysql -u root -p password 登入数据库,没有切换到任何数据库,才可以执行操作数据库的操作
// 显示所有数据库
show databases;
// 创建数据库
-- create database 数据库名 charset=utf8;
create database python04new charset=utf8;
CREATE DATABASE `ihbs` CHARACTER SET 'utf8' COLLATE 'utf8_general_ci';
// 查看创建数据库的语句
-- show create database `数据库名`;
show create database python04;
// 删除数据库
-- drop database 数据库名; drop database if exists `数据库名`;
DROP DATABASE IF EXISTS `ihbs`;
//使用数据库
--use 数据库的名字
use python02new;
// 查看当前使用的数据库
select database(); # function
create table 表名(
列名1 列2类型 [完整性约束条件],
列名2 列2类型 [完整性约束条件],
……
)ENGINE = myisam|innodb default charset = utf8|gbk|latin1;
-- auto_increment表示自动增长
-- not null 表示不能为空
-- primary key 表示主键
-- default 默认值
-- enum 枚举
-- create table 数据表名字 (字段 类型 约束[, 字段 类型 约束]);
eg:
create table zzzz(
id int primary key not null auto_increment,
name varchar(30) # 最后一个末尾不能加 ',' 逗号, 否则会报错
);
create table students(
id int unsigned not null auto_increment primary key,
name varchar(30),
age tinyint unsigned default 0,
high decimal(5,2),
gender enum("男", "女", "中性", "保密") default "保密",
cls_id int unsigned
);ENGINE=InnoDB default charset=utf8
//查看该表的结构
desc 表名 --> describe 表名
show create table 表名;
//查看表的创建信息
show create table students;
单字段主键
create table table2(
stu int PRIMARY key,
name VARCHAR(30)
);
多字段主键
create table table2(
stu int ,
name VARCHAR(30),
primary key (stu,name)
);
完整demo
create table if not exists test(
id int PRIMARY key auto_increment COMMENT '主键,自增',
name VARCHAR(30) UNIQUE COMMENT '唯一性约束',
sex int DEFAULT 1 COMMENT '设置默认值',
dsc VARCHAR(256) not null COMMENT '非空',
forid int COMMENT '和table2表的stu进行外键约束',
constraint forkey FOREIGN KEY(forid) references table2(stu)
);
// 修改表名:
alter table 旧表名 RENAME [to] 新表名
// 添加列
alter table 表名 add 属性名 属性类型 [完整性约束条件] [First | After 属性名]
alter table 表名 add 属性名 属性类型 after 某列名(指定添加到某列后)
alter table 表名 add 属性名 属性类型 first;(把新列加到最前面)
// 删除列
alter table 表名 drop 属性名
// 修改列
alter table 表名 modify 属性名 属性类型;
// 修改列名及列类型:
alter table 表名 change 旧属性名 新属性名 新类型;
// 修改字段的排列顺序
alter table 表名 modify 属性1 数据类型 first | after 属性2
// 修改表的存储引擎
alter table 表名 engine = 存储引擎名
注意
字段改名后,完整性约束条件丢失
// 以下修改后,约束条件还在
alter table teacher change num t_id not null unique
// 以下修改后,t_id约束条件丢失
alter table teacher change num t_id
结论:属性改名时,必须在语句中加上原来的完整性约束条件12345
// 删除没有被关联的表
drop table 表名
// 删除被其他表关联的表
先删除外键约束: alter table 表名2 drop foreign key 外键别名
再删除表:drop table 表名12345
curd的解释:
增加
-- 全列插入: 值的顺序与表中字段的顺序对应
//insert [into] 表名 values(...)
//主键字段 主键列是自动增长,但是在全列插入时需要占位,通常使用0或者 default 或者 null 来占位,插入成功后以实际数据为准
insert into students values(0,’郭靖‘,1,'蒙古','2016-1-2');
-- 部分列插入:值的顺序与给出的列顺序对应
// 如果有默认值,系统自动填默认值; 没有填 null
insert into students(name,hometown,birthday) values('黄蓉','桃花岛','2016-3-2');
insert into student(name,age) values("you",18);
-- 多行插入: 一次性插入多行数据
// 各个记录之间用 逗号隔开 (), ()
//全列多行插入:值的顺序与给出的列顺序对应
insert into classes values(0,'python1'),(0,'python2');
insert into students(name) values('杨康'),('杨过'),('小龙女');
删除 delete from ... where ...
-- 物理删除
-- delete from 表名 where 条件
delete from students; -- 整个数据表中的所有数据全部删除
delete from students where name="小李飞刀";
uadate CLASS set FIELD CONSTRAIT where 哪些行
-- 逻辑删除
-- 用一个字段来表示 这条信息是否已经不能再使用了
-- 给students表添加一个is_delete字段 bit 类型
alter table students add is_delete bit default 0;
update students set is_delete=1 where id=6;
修改
--update 表名 set 列1=值1,列2=值2... where 条件;
update students set gender=1; -- 全部都改
update students set gender=1 where name="小李飞刀"; -- 只要name是小李飞刀的 全部的修改
update students set gender=1 where id=3; -- 只要id为3的 进行修改
update students set age=22, gender=1 where id=3; -- 只要id为3的 进行修改
查询基本使用
select 字段 from 表名 --> 查看 哪些字段 从 哪个表
-- 查询所有列
-- select * from 表名;
select * from students;
---定条件查询
select * from students where name="小李飞刀"; -- 查询 name为小李飞刀的所有信息
select * from students where id>3; -- 查询 name为小李飞刀的所有信息
-- 查询指定列
-- select 列1,列2,... from 表名;
select name,gender from students;
-- 可以使用as为列或表指定别名
-- select 字段[as 别名] , 字段[as 别名] from 数据表 where ....;
select name as 姓名,gender as 性别 from students;
-- 字段的顺序
select id as 序号, gender as 性别, name as 姓名 from students;
// 插入数据
insert into 表名(属性名1,属性名2,...) values(值1,值2,...),[(值1,值2,...)...]
// 将查询结果插入到表中
insert into 表名1(属性列表1) select 属性列表2 from 表名 where 条件表达式
// 更新数据
update 表名 set 属性1=值1, 属性2=值2,.... where 表达式
// 删除数据
delete from 表名[ where 表达式]
视图简介:
视图作用
区别
联系
必须拥有创建视图权限(Create View权限)
// 语法
create [Algorithm={Undefined|Merge|Temptable}]
View 视图名[(属性列表)]
As select 语句
[With [Cascaded | Local]] check option];
Algorithm:
Undefined:mysql默认算法
Merge:将使用视图的语句与视图定义合并起来,使得视图定义某一部分取代语句对应部分
TempTable:将视图结果存入临时表,然后临时表执行语句
With:
cascaded:更新视图时要满足所有相关视图和表条件(默认)
Local:更新视图时需要满足视图本身的定义条件即可
// 在单表上创建视图
create view v_appuser As SELECT * from qappuser
// 在多表上创建视图
create ALGORITHM=MERGE view v_appuser2
As SELECT a.* from qappuser as a, qappfunction as b
WITH LOCAL check option;
// 查看视图
DESC v_appuser;
describe v_appuser2;
show table status like 'v_appuser';
show create view v_appuser;
SELECT * from information_schema.VIEWS;
12345678910111213141516171819202122232425262728
// 修改视图:Create or Replace语法
Create or Replace [Algorithm={Undefined|Merge|Temptable}]
View 视图名[(属性列表)]
As select 语句
[With [Cascaded | Local]] check option];
说明:不存在时创建视图,存在时,则修改视图
// 修改视图:Alter语法
Alter [Algorithm={Undefined|Merge|Temptable}]
View 视图名[(属性列表)]
As select 语句
[With [Cascaded | Local]] check option];
说明:使用alter时,视图名必须存在12345678910111213
// 创建测试视图
CREATE
View v_appuser
As SELECT * from qappuser where iAppuserId = 1430224175105
// 更新视图记录
// 通过视图更新时,只能更新权限范围内数据
update v_appuser set sUsername="11"
说明:以上语句只更新iAppUserId=1430224175105的记录,而其他记录不更新
// 不能更新的视图
○ 视图中包含sum、count、max、min
○ 视图中包含union、union all、distinct、group by、having
○ 常量视图:create view t_view as select 'name' as name
○ 视图中select中包含子查询:create view t_view7(name) as select (select name from qwork)
○ 由不可更新视图导出的视图
○ 创建视图时,Algorithm为Temptable类型
视图对应表上存在没有设置默认值的列,而且改列没有包含在视图中123456789101112131415161718
drop view if exists 视图名列表 [Restrict | cascade]
// 触发事件
Insert、update、delete
// 创建一个只有一个执行语句的触发器
create trigger 触发器名 before | after
触发事件
on 表名 for each row 执行语句
// 创建多个执行语句触发器
create trigger 触发器 before | after
触发事件
on 表名 for each row
before
执行语句列表
end
// 查看触发器
show triggers \G;
// information_schema 下的triggers表
SELECT * from information_schema.TRIGGERS;
// 触发器使用顺序
Before触发器 操作(insert,update,delete) After触发器
// 删除触发器
Drop trigger 触发器名1234567891011121314151617181920212223
创建触发器demo:
create trigger updatename after update on user for each row //建立触发器,
begin
//old,new都是代表当前操作的记录行,你把它当成表名,也行;
if new.name!=old.name then //当表中用户名称发生变化时,执行
update comment set comment.name=new.name where comment.u_id=old.id;
end if;
select 属性列表
from 表名和视图列表
[where 条件表达式]
[Group by 属性1 [having 条件表达式2] ]
[Order by 属性2 [ASC|DESC]]
带like查询
[Not] like
带"%"通配符,多个字符
带"_"通配符,一个字符
带in关键字查询
[Not] in (元素1,元素2,...)
带between and 查询
[Not] between 值1 and 值2
空值查询
is [not] null
带and、or查询条件
带distinct查询
带比较条件:
=、<、<=、>、>=、!=、<>、!>、!<
使用limit限制查询结果数目(从0开始)
不指定初始位置,只指定显示N个
select * from employ limit 2;
指定初始位置
select * from employ limit 0,2;
12345678910111213141516171819202122232425
内连接:两边都有才被查询
外连接:
将一个查询语句嵌套在另一个查询语句中。内层查询语句的查询结果可以为外层查询语句提供查询条件
带比较运算符子查询
带[Not] exists关键字查询
SQL中EXISTS的用法
带any关键字子查询
带all关键字子查询
合并查询结果
分组查询:带有GROUP BY的查询,也叫组合查询
特征
例如:
SELECT
SUBSTR(A.HYLB_DM,1,2),
COUNT(*),
SUM(A.ZCZB)
FROM DJ_ZT A
GROUP BY SUBSTR(A.HYLB_DM,1,2)
HAVING MAX(YEAR(A.CJRQ))<>2007;1234567
带有WHERE和HAVING的SELECT语句执行过程:
§ 执行WHERE筛选数据
§ 执行GROUP BY分组形成中间分组表
§ 执行WITH ROLLUP/CUBE生成统计分析数据记录并加入中间分组表
§ 执行HAVING筛选中间分组表
§ 执行ORDER BY排序
// 查看某个表的索引
show index from 表名;
123
可以创建在任何数据类型上,不附件任何限制条件
// 创建表时创建索引
drop table if EXISTS test;
CREATE table test(
id int,
name VARCHAR(20),
sex TINYINT,
INDEX(id)
);
// 在已存在的表上创建索引
语法:Create [Unique | Fulltext | spatial] index 索引名 on 表名(属性名[(长度)][ASC|DESC], ...);
create INDEX index_id on test(id);
// 用Alter table创建索引,其他也是类似,不在一一举例
// Alter table 表名 add [Unique | Fulltext | spatial] Index 索引名 (属性名[(长度)][ASC|DESC],...)
ALTER TABLE test add UNIQUE INDEX index_id4(id);
// 删除索引,所有类型的索引的删除语句都是一样的
drop index index_id2 on test;
1234567891011121314151617
只能在唯一值数据上创建索引,用Unique参数设置
// 创建表时创建索引,Mysql中不用加unique index(id),只要某个字段是unique就自动建立唯一索引。
drop table if EXISTS test;
CREATE table test(
id int unique,
name VARCHAR(20),
sex TINYINT,
// id_index表示索引名称,(id asc)表示索引升序排列
unique INDEX id_index(id asc)
// unique INDEX (id )
);
// 在已存在的表上创建索引,其他在已有的表建立索引,语法相似就不一一举例
create UNIQUE INDEX index_id2 on test(id);
// 用Alter table创建索引12345678910111213
只能在char、varchar和text上建立索引,用fulltext设置,只限于MyIsam存储引擎
// 创建表时创建索引
drop table if EXISTS test;
CREATE table test(
id int unique,
name VARCHAR(20),
sex TINYINT,
FULLTEXT INDEX name_index(name )
)ENGINE=myisam;12345678
在表的单个字段上建立索引
// 创建表时创建索引
drop table if EXISTS test;
CREATE table test(
id int unique,
name VARCHAR(20),
sex TINYINT,
// 只取前10个前缀建立索引
INDEX name_index(name(10) )
);123456789
在表的多个字段上建立索引。只有查询条件中使用了这些字段中的第一个字段时,索引才被使用。
例子:如在id,name和sex上建立了多列索引,只有在查询条件中使用了id字段,该索引才被使用
// 创建表时创建索引
drop table if EXISTS test;
CREATE table test(
id int unique,
name VARCHAR(20),
sex TINYINT,
INDEX name_index(name(10),sex )
);12345678
只能在空间数据类型上建立索引
// 为Entry数据库创建一个remote_entry账号,密码为password,拥有select、insert、delete、create、drop权限
grant select,insert,update,delete,create,drop on entry.* to 'remote_entry'@'%' identified by 'password';
// 不用刷新权限,就可以登录;如果通过insert、update对mysql.user进行操作,则需要进行刷新操作
// flush privileges;1234
DROP USER 'remote_entry'@'%';1
SELECT * from mysql.user1
// 登录后,修改自己密码
set Password = Password("new_password");
// 账号拥有Super_priv的权限,才可以执行以下操作,如root用户
mysqladmin -umysql -ppassword password "password2"
// 拥有修改mysql表权限的用户(如root用户)修改自己或者别人密码,并刷新权限
update mysql.user set password=Password("password") where user='remote_entry' and host='localhost';
flush privileges;
// 修改别人密码
set Password for 'remote_entry'@'%' = Password("password") ;123456789
// 修改用户只能本地访问,如果要任何IP都可以访问,则设置host为%;需要刷新权限
update mysql.user set host = 'localhost' where user='mysql';
flush privileges;
1234
// 1 打开命令行界面,使用 --skip-grant-tables方式启动服务,在命令行中执行,程序会停留在界面上
mysqld --skip-grant-tables
// 2 打开新命令行界面,使用root无密码登陆,并执行密码修改语句,并刷新权限
mysql -uroot
update mysql.user set password=Password("password2") where user = "root";
flush privileges;123456
// with grant option(未测试,是否可以给其他用户授权)表示对A用户进行的授权,A可以授予给其他用户,当收回对A的授权时,A授予给其他用户的权限不会被级联收回
grant select,update on *.* to 'entry'@'localhost' identified by 'entry' with grant option;
// 为一个用户赋予全部的权限
grant all privileges on ab.* to hwalk1@'%' identified by 'hwalk1';1234
// 收回所有用户或者某个特定数据库的权限
Revoke all privileges on *.* from 'entry'@'localhost';
123
// 获取用户在所有数据库上的权限
select * from mysql.user \G;
// 查看用户所有权限,在所有数据库和特定数据库上的权限
show grants for 'root'@'localhost';