MySQL知识点总结

MySQL知识点总结

一、      MySQL常用命令

  1. 启动MySQL服务:service mysqld start 或 systemctl start mysqld.service
  2. 停止MySQL服务:service mysqld stop 或 systemctl stopt mysqld.service
  3. 重启MySQL服务:service mysqld restart 或 systemctl restart mysqld.service
  4. 查看MySQL服务状态:service mysqld status 或 systemctl status mysqld.service
  5. 连接MySQL:mysql –uroot –p
  6. 退出mysql服务:exit
  7. 查看用户数据库权限:show grants;
  8. 查看数据库:show databases;
  9. 重命名数据库:rename database 原数据库名 to 新数据库名
  10. 删除数据库:drop database 数据库名;
  11. 使用数据库:use 数据库名;
  12. 查看数据库包含的表:show tables;
  13. 重命名表:alter table 原表名 rename to 新表名;

还可使用:rename table 数据库.原表名 to 数据库.新表名; (可用于表在数据库的迁移)

  1. 创建表:create table if not exists 表名(表头1 数据类型(数据长度) primary key,表头2,数据类型(数据长度))engine=innodb default charset=utf8;
  2. 复制表:create table 新表名 as ( select * from 表 [where 条件]);
  3. 只复制表结构:create table 新表名 as ( select * from 表 where null);
  4. 查看表结构:desc 表名;
  5. 新增字段:alter table 表名 add 表头 数据类型(数据长度);
  6. 删除字段:alter table 表名 drop 表头 ;
  7. 修改字段:alter table 表名 modify 原表头 新表头 数据类型(数据长度);
  8. 添加外键:alter table 表名 add constraint 索引名(一般以fk_开头) foreign key(外键名) references 关联外键的表名(关联的主键字段);
  9. 插入数据:insert into 表名 ( 列名1,列名2,...,列名n ) values ( 值a1,值a2,...,值an ), ( 值b1,值b2,...,值bn ),…;
  10. 删除数据:delete from 表名 [where 子句];
  11. 快速删除数据:truncat 表1;删除表1后创建一个新的表,结构名称与表1相同;
  12. 修改数据:update 表名 set 列名1=新值1, 列名2=新值2 [where子句];
  13. 查询数据:select 列名1,列名2 from 表名 [where子句];
  14. 引入sql脚本:source 文件路径/文件.sql
  15. 修改访问权限GRANT ALL PRIVILEGES ON 数据库.* TO 'root'@'%' IDENTIFIED BY '123456';
  16. 刷新权限flush privileges;

二、      MySQL where子句

使用where子句查询可分为精确查询和模糊查询

比较符有:=、>、<、=、>=、<=、!=、<>

逻辑符号有:and、or 、not

范围运算符:between … and ..、in、not in

模糊运算:like ‘%_’:%匹配任意字符,_匹配单个字符;

空运算:null、is null、not … is null

子查询:select 字段 from 表 where 字段 in ( select…from…);

三、      group by

select 字段 from 表 group by 字段 having 条件;

having作用与where相似,不能与where一起用,可单独用where:select 字段 from 表 where 条件group by 字段 。

四、      order by

select 字段 from 表 order by 字段1 排序,字段2 排序,….

MySQL中默认为升序排序:asc;降序排序显示为desc。

五、      limit

select 字段 from 表 limit n1 :查询表前n1条数据;

select 字段 from 表 limit n1,n2:查询表行号为n1行为开始行的n2条数据。

六、      查询常用函数

查询语句中常用函数有求和sum()、最大值max()、最小值min()、平均值avg()、统计行数count()、连接查询结果concat() as 、去除重复项distinct

count( )

count(1)和count(*)包含null值,统计行数等于原表记录行数;

count(非空字段) 不计算null值,统计行数等于原表记录行数;

count(null值字段)不计算null值,统计行数小于等于原表记录行数;

count(null)结果恒为0。

concat(‘常量’,字段) as ‘别名’

concat()函数可以将查询结果连接在一起作为一列输出。

七、      多表查询

当需要使用多表进行查询时,需要先考虑查询的数据来源(表),再分析表与表之间的联系;

多表查询除了外连接和内连接,还可以自连接进行查询。

内连接:… inner join…on…

select 字段 from 表join表2 on 联系字段 join表3 on 联系字段

外连接:left join, right join

左外连接:表1 left join 表2 on 联系字段;保留左边的表的全部数据,不管右边是否有对应数据匹配;

右外连接:表1 right join 表2 on 联系字段; 保留右边的表的全部数据,不管左边是否有对应数据匹配;

八、      union

union把多个sql语句的执行结果,合并到1个结果中;sql语句的查询字段必须相似,否则会报错。

union操作符: 默认会去除多个结果中的重复信息;

union all 操作符: 返回多个结果中所有信息(不会去除重复信息)。

posted @ 2020-06-28 15:59  树下影  阅读(546)  评论(0编辑  收藏  举报