MySQL之常用SQL操作

SQL

DDL:定义数据库对象(数据库、表、字段)

  1. 查询
show databases;   --查询所有数据库
show  tables;
desc 表名; --查询表结构
show create table 表名 ; 插叙指定表的建表语句
select database();    --查询当前数据库
  1. 创建
create database [if not exists] 数据库名 [default charset utf8mb4] [collate 排序规则]; 
create table 表名(
	字段1 字段1类型 [comment 字段1注释],
	age int comment "年龄",
	name varchar(20) comment "用户名",
	...
)[comment 表注释];
  1. 删除
drop database [if exists] 数据库名;
drop table [if exists] 表名;
truncate table 表名;  --删除指定表,并重新创建该表
alter table 表名 drop 字段名;  --删除字段
  1. 使用
use 数据库名;
  1. 修改
alter table 表名 add 字段名 类型(长度)[comment 注释];
alter table 表名 modify 字段名 新数据类型(长度);  --修改数据类型
alter table 表名 旧字段名 新字段名 类型(长度)[comment 注释] [约束];  --修改字段名和字段类型
alter table 表名 rename to 新表名;   --修改表名

DML:对数据库表中的语言增、删、改

  1. 添加数据
insert into 表名(字段名1,字段名2...values(1,值2...);
insert into 表名 values(1,值2...);   --给全部字段添加数据
insert into 表名(字段名1,字段名2...values(1,值2...)(1,值2...)(1,值2...);  --批量添加
insert into 表名 values(1,值2...)(1,值2...)(1,值2...); 
  1. 修改数据
update 表名 set 字段名1 =1,字段名2 =2 [where 条件];
  1. 删除数据
delete from 表名 [where 条件];

DQL:查询数据库中表的记录

DQL执行顺序:from 、where、 group by、 having select 、order by、limit

select 字段1,字段2 ... from 表名;
select 字段1 [as 别名1]... from 表名;   -- 设置别名
select distinct 字段列表 from 表名;    --去重
select count/max/min/avg/sum(字段列表) from 表名;
select 字段列表 from 表名 [where 条件] group by 分组字段名 [having 分组后过滤条件];
-- asc 升序(默认可省略) desc降序
select 字段列表 from 表名 order by 字段1 排序方式1,字段2 排序方式2... ; 
select 字段列表 from 表名 limit 起始索引,查询记录数
--起始索引 = (查询页码-1)*每页记录数

案例:

--1、根据性别分组,统计男性员工和女性员工的平均年龄
select gender,avg(age) from emp group by gender;
--2、查询年龄小于45,根据工作地址分组,获取员工数量大于3的工作地址
select workaddress,count(*) from emp group by workaddress having count(*)>=3;

DCL:创建数据库用户、控制数据库访问权限

  • 用户管理
  1. 查询用户
user mysql;
select * from user;
  1. 创建用户
create user '用户名'@'主机名' identified by '密码';
  1. 修改用户密码
alter user '用户名'@'主机名' identified with mysql_native_passord by '新密码';
  1. 删除用户
drop user '用户名'@'主机名';
  • 权限控制
  1. 查询权限
show grants for '用户名'@'主机名';
  1. 授予权限
grant 权限列表 on 数据库名.表名 to '用户名'@'主机名';
  1. 撤销权限
revoke 权限列表 on 数据库名.表名 from '用户名'@'主机名';
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值