MySQL基础:SQL基础

65 阅读2分钟

DDL(数据库定义语言)语句

数据库命令操作

登录:mysql -uroot -p

创建数据库:create database test1

显示数据库:show databases

选择库:use test1

显示所有表:show tables

删除数据库:drop database test1

创建表:

create table emp (ename varchar(10), hiredate date, sal decimal(10,2), deptno int(2))

查看表结构:desc emp

查看创建表的SQL语句:show create table emp \G

注:此操作还能看到表的存储引擎(engine=InnoDB)和 字符集(charset=GBK)

\G 表示查看记录按照字段竖向排列(显示效果)

删除表:

drop table emp

修改表:

(1)修改表类型—— alter table emp modify ename varchar(20)

(2)增加表字段—— alter table emp add column age int(3)

(3)删除表字段—— alter table emp drop column age

(4)修改字段名—— alter table emp change age age1 int(4)

(5)修改表名—— alter table emp rename emp1

DML(数据库操纵语言)语句

插入:insert into

insert into emp(ename, hiredate, sal, deptno) values('zhangsan', '2000-02-05', '2000', 1)

insert into emp values('zhangsan', '2000-02-05', '2000', 1)

insert into emp values('li', '2000-02-05', '2001', 2) 一次插入多条

更新:update ... set

update emp set sal=40 where ename='lisa'

update emp a, dept b set a.sal=b.sal where a.deptno = b.deptno

删除:delete

delete from emp where ename='dony'

查询:select

select * from emp

(1)条件去重查询:distinct

select distinct deptno from emp

(2)条件查询:where

select * from emp where deptno = 1

(3)排序查询:order by (ASC、DESC)

select * from emp order by sal desc

(4)限制查询:limit

select * from emp order by sal limit 1,5

(5)分组/聚合查询:group by

select deptno, count(1) from emp group by deptno

注:having 和 where的区别——where 是在分组前过滤;having 在分组后过滤。

使用 where 查询效率比 having 高

select deptno, count(1) from emp group by deptno having count(1) > 1

(5)表连接

内连接:

外连接:左连接、右链接

select ename, deptname from emp left join dept on emp.deptno=dept.deptno

select ename, deptname from emp right join dept on emp.deptno=dept.deptno

(6)子查询:in、not in、=、!=、exists、not exists

select * from emp where deptno in(select deptno from dept)

注:如果子查询记录数唯一,可以用=代替——select * from emp where deptno = (select deptno from dept)

(7)联合查询:union、union all

select deptno from emp

union

select deptno from dept

注:union 与 union all 的区别——union是将两个表的查询结果合并显示;union all 是两表结果去重后显示(相当于结果做一次distinct操作)

DCL(数据控制语句)语句

用于数据库的安全级别与访问权限设置,一般开发中很少使用