1.基础SQL命令
SQL 语句用于维护管理数据库,包括数据查询、数据更新、访问控制、对象管理等功能
SQL语言分类:
DDL 数据定义语言,用于创建数据库对象,如库、表、索引等
DML 数据操纵语言,用于对表中的数据进行管理
DQL 数据查询语言,用于从数据表中查找符合条件的数据记录
DCL 数据控制语言,用于设置或者更改数据库用户或角色权限
1.1DDL
DDL是定义语言,常用语句:CREATE、 ALTER、DROP
- create:创建数据库、表
create database + 数据库名;
create table + 数据表名+(字段1 数据类型,字段2 数据类型,....);
- drop:删除数据库、表
drop database + 数据库名;
drop table + 数据表名;
- alter 修改表结构
alter table stu change name names varchar(32);
扩展:
1.TRUNCATE TABLE:删除内容、释放空间但不删除定义,也就是不删除表结构
2.DELETE TABLE:删除内容不删除定义,不释放空间。
3.DROP TABLE:删除内容和定义,释放空间。
1.2 DML
DML是操作语言,常用语句:INSERT、 UPDATE、 DELETE
- insert 增加表数据
create table stu(id int,name varchar(32),age int);
insert into stu(id,name,age) values(1,'张三',20),(2,'李四',21),(3,'王五',22);
- update更新修改表数据
update stu set names='赵六' where id=3;
- delete:删除表数据
1.3DQL
DQL:数据查询语言,用来查询数据常用语句:SELECT
SELECE语法:
SELECT[ALL | DISTINCT]
{* | table.* |[table.field1[as alias1][,table.field2[as alias2]][,...]]}
from table_name [as table_alias]
[left | out|inner join table_name2]
[where ...]
[group by...]
[having...]
[order by...]
select * from 表名:不推荐使用,效率低
- 查询表中信息
select * from stu;//查询stu表数据信息
select * from stu\G //另一种形式
- 别名查询
select s.names,s.age from stu as s; //使用别名查询表元素数据,另两种格式如下
select s.names as n,s.age as a from stu s;
select s.names n ,s.age a from stu s
- 查找数据去除重复项
select distinct(age) from stu;
- 查询元素区间的数据
select * from stu where age between 28 and 30;
模式2:select * from stu where age>=28 and age<=30;
- 模糊查询数据
select * from stu where names like '王_';//查询名字含王某的信息
模式2:select * from stu where names like '%王_';
模式3:select * from stu where names like '%王_%';
- 过滤查询
select * from stu where age in(20,24,30); //查询年龄为20、24、30的信息
1.4DCL
DCL:数据控制语言,用来操作访问权限和安全级别;常用语句:GRANT、DENY