MySQL 命令大全
基础知识
– SQL (Structured Query Language - 结构化查询语言)
– DDL (数据定义语言) create / drop / alter
– DML (数据操作语言) insert / delete / update
– DQL (数据查询语言) select
– DCL (数据控制语言) grant / revoke
linux启动服务器命令:systemctl start mariadb
windows启动服务器命令:net start mysql57
登陆服务器:mysql -u -root -p (用root登陆数据库-p表示密码)
开机自启/不自启:systemcrl enable/disable mariadb
停止数据库服务器:systemctl stop mariadb.service
登陆远程数据库服务器:mysql -h xxx.xxx.xxx.xxx -u xxx -p
服务器中显示所有数据库:show databases;
选择进入mysql数据库:use mysql;
显示数据库中所有表格:show tables;
常用知识
(CRUD)增删改查:
-- 添加数据
insert into tb_dept (deptno, dname) values (40, '销售部2'), (50, '后勤部'), (60, '技术部');
-- 删除数据,(注意:一定要带上条件)
delete from tb_dept where deptno=50;
-- 查所有行列
select * from tb_dept;
-- 投影
select deptno, dname from tb_dept;
-- 别名
select deptno as 部门编号, dname as 部门名称 from tb_dept;
-- 筛选
select deptno, dname from tb_dept where dloc='深圳';
-- 修改表
update student set s_name='李四' where id=1;
-- 创建字段add
alter table student add s_grades int;
-- 删除字段drop
alter table student drop s_grades;
-- 更改字段change
alter table student change s_grades s_price int;
-- 修改表中数据
update student set s_price=80 where id=1 or id=4 or id=7;
-- 删除列
alter table tb_dept drop column s_id;
-- 增加一列
alter table student add s_id int;
-- 找最大
select max(s_price) from student;
-- 找最小
select min(s_price) from student;
-- 求平均
select avg(s_price) from student;
-- 查询表结构
desc grade;
-- 按照id排序显示(order by() - 表示倒序 + 表示正序(可省略))
select * from student order by(-id);
-- limit 限制返回的数据条数
select * from student limit 1;
-- offset 指定开始查询位置的偏移量 默认是0 (要与limit结合使用)
select * from student limit 1 offset 1;
-- 求薪水排在第4-8名的员工
select * from tbemp ORDER BY sal desc limit 3,5
--
select * from tbemp ORDER BY sal desc limit 5 offset 3 -- desc 降序
创建一个数据库test和一个表student:
create databases test charset utf8;
-- auto_increment 表示自增
create table student(
-> id int auto_increment not null,
-> s_name varchar(30) not null,
-> primary key(id) -- 每个表都必不可少(主键)
->);
创建索引、外键、cascade:
mysql
alter table tableone add constraint fk_sid foreign key (sid) references tabletwo (stuid) on delete cascade on update cascade;
having 用法
mysql
select stuname from tbstudent where stuid in (select sid from tbsc group by sid having count(*) > 2);
去重
select distinct scdate from tbsc; -- distinct
空值处理
select stuname from tbstudent where stuaddr is null and stuphoto is null;
-- ------------------------------------
select sid, ifnull(score, 0) as score from tbsc
-- ----------------
ifnull(expr1,expr2) -- expr1为null返回expr2,否则返回expr1
isnull(expr) -- expr为null返回1,否则为0
nullif(expr1,expr2) -- expr1=expr2则返回null,否则返回expr2
模糊查询
-- %:表示任意0个或多个字符
select * from xxx where name like '%王%';-- 表示返回name中含有‘王’字的数据
-- _: 表示任意单个字符
select * from xxx where name like '_王_';-- 表示返回name有三个字且中间字为‘王’字的数据
-- [ ]:表示括号内所列字符中的一个(类似正则表达式)
select * from xxx where name like '[李张王]三'; -- 将找出“张三”、“李三”、“王三”(而不是“张李王三”);
-- [^ ] :表示不在括号所列之内的单个字符。
select * from xxx where name like '老[^1-4]'; -- 排除“老1”到“老4”,寻找“老5”、“老6”、……