MySQL常用增删查改语句(详细)

MySQL常用增删查改语句:

表的基本操作:

登入数据库:mysql -h localhost -u root -p/mysql -u root -p

查看所有数据库:show databases;

创建数据库:create databases 数据库名;

使用数据库:use 数据库名;

查看所创建的数据库:show create databases 数据库名;

设置数据库语言:alter databases 数据库 default character set gbk/utf-8 collate ut-8_bin/gbk_bin;

删除数据库:drop databases 数据库名;

查看数据库表:show tables;

查看创建表: show create table 表名;

修改表名:alter table 表名 rename 新表名;

修改字段:alter table 表名 change 原字段名 新字段名 新数据类型;

修改数据类型:alter table 表名 modify 字段名 数据类型;

删除字段: alter table 表名 drop 字段名;

修改字段顺序:alter table 表名 modify 字段名1 数据类型 frist/after 字段名2 ;

删除表:drop table 表名;

向表中插入数据: insert into table (字段1,字段2.....) values(值1,值2,.......),(值1,值2,......);

查看表:select * from 表名;

更新数据:update 表名 set 数据 where 条件;

删除表:delete from表名;

删除表中数据:delete from表名 where 删除的数据;

表的基本查询:

查看数据:select * from 表名 where 查看的数据条件;

and语法:select * from 表名 where 条件表达式 and 条件表达式2;

Or语法:select * from 表名 where 条件表达式 or 条件表达式2;

In/not in语法:select * from 表名 where 条件表达式 in/not in 条件表达式2;

Null语法:select * from 表名 where 条件表达式 is null/not null 条件表达式2;

between语法:select * from 表名 where 条件表达式 between/not between 条件表达式2;

模糊查询like:select * from 表名 where 字段 like/not like “%z”;(%z%,z%,Z_%等)

去掉重复查询:select distinct 表名 from 表名;

升序降序查询:select * from 表名 order by 字段名 desc/asc;

数量统计: select count(字段名) as total from 表名;

Select count(*) as total from 表名 where 查询条件;

求数据总和:select sum(知字段名) from 表名;

求数据平均值:select avg(字段名) from 表名;

求数据最大值:seelct max(字段名) from 表名;

求最小值:seelct min(字段名) from 表名;

分组查询:select * from 表名 group by 字段名;

Select 字段名,sum(字段名) from 表名 where 条件 group by 字段名;

限制查询:select * from 表名 limit 2,5;

数据的完整性:

添加主键:alter table 表名 add primary key (字段);

删除字段:delete from 表名 where 字段名;

创建主键:create table 表名 ( 字段名 数据类型 primary key,字段名2 数据类型二.....);

创建主键:create table 表名 ( 字段名 数据类型,字段名2 数据类型二.....,primary key (字段名))

创建唯一约束:create table 表名(字段名 数据类型 unique,字段名2 数据类型,......);

Alter table 表名 add unique (字段名);

设置主键和自增:alter table 表名 modify 字段名 数据类型 primary key auto_increment;

创建唯一索引:create unique index 索引名 on 表名(字段名);

设置为不为空:alter table 表名 modify 字段名 数据类型 not null;

设置默认值:alter table 表名 modify 字段名 数据类型 default 默认值;

修改外键:alter table 表名 add foreign key(外键名) references 主表名(主键字段名);

创建外键:create table 表名(字段名 数据类型,.......,foreign key(外键字段名) references 表表名(主键字段名));

删除主键:alter table 表名 drop foreign key 外键名;

删除索引:alter table 表名 drop index 索引名;/ drop index 索引名 on 表名;

条件查询先后顺序:where>group by>order by>limite

数据的备份:

mysqldump -u root -p db_name > file.sql

mysqldump -u root -p db_name table_name > file.sql

#数据库还原

mysql -u root -p < C:\file.sql

猜你喜欢

转载自blog.csdn.net/Z_CH8648/article/details/126919864
今日推荐