SQL单表语句(DDL,DML,DQL)

SQL分类

  1. 数据定义语言,DDL,(库表操作)
  2. 数据操作语言,DML,(增,删,改)
  3. 数据查询语言,DQl,(查)

DDL操作

库操作

//建立数据库并指定字符集
create database 库名 character set 编码;
//查看所有数据库
show databases;
//查看表库的编码
show create database 库名;
//删除数据库
drop database 库名;
//使用数据库
use 库名;
//查看正在使用的数据库
select database();

表操作

//创建表
create table 表名(
    字段名 类型(长度) [约束],
    字段名 类型(长度) [约束]
);

//单表约束
1. 主键约束:primary key
2. 唯一约束:unique
3. 非空约束:not null

//示例
mysql> create table tbl_user(
    -> uid int(32) primary key auto_increment,
    -> uname varchar(32),
    -> upassword varchar(32)
    -> );

//查看所有表
show tables;

//查看表的结构
desc 表名

//删除表
drop table 表名;

//修改表
//添加一列
alter table 表名 add 字段名 类型(长度) [约束];
//修改列的类型
alter table 表名 modify 字段名 类型(长度) [约束];
//修改列名
alter table 表名 change 旧列名 新列名 类型(长度) [约束];
//删除表的列
alter table 表名 drop 列名;
//修改表名
rename table 旧表名 to 新表名;
//修改表的字符集
alter table 表名 character set 编码;

DML操作

insert

//语法
insert into 表 (列名1,列名....) values (值1,值...);

insert into 表 values(值1,值...);

注意:值如果是字符串或日期需要加引号''(一般是单引号)

update

//语法
update 表名 set 字段名=值,字段名=值....;

update 表名 set 字段名=值,字段名=值.... where 条件;

delete

//语法
delete from 表名 [where 条件];

delete与truncate区别?

  1. delete删除的时候是一条一条的删除记录,它配合事务可以将删除的事务找回
  2. truncate是将整个表删除,然后再创建一张一摸一样的表.删除的数据无法找回

DQL操作

普通查询

//语法
select [distinct] * | 列名1,列名... from 表名 [where 条件]

注意:不推荐使用*

//使用表别名
select ... from 表名 as 别名;(as可以省略)

//使用列别名
select 列名 as 别名 from 表名;(as可以省略)

//去掉重复的值(按某列)
select distinct(列名) from 表名;

//将某列+10并显示(计算)
select 列名+10 from 表名;

//条件查询
select * from 表名 where 条件;

//包含某个字段查询
select * from 表名 where 列名 like '字段';

//集合范围条件查询
select * from 表名 where 列名 in (集合);

//多条件查询
select * from 表名 where 条件1 and 条件2;

//任一条件符合查询
select * from 表名 where 条件1 or 条件2;

//非此条件查询
select * from 表名 where not 条件1;

//按某列排序
select * from 表名 where 条件 order by 列名 asc(升)|desc(降);

聚合查询

注意:聚合函数不统计null值.

//获取总和
select sum(列名) from 表名;

//获取平均
select avg(列名) from 表名;

//获取个数
select count(*) from 表名;

分组查询

//按某列的值分组
select * from 表名 group by 列名;

//带条件分组(不能使用where)
select * from 表名 group by 列名 having 条件;

查询总结:

select distinct * | 字段1,字段...
from 表
where 条件
group by 分组字段
    having 分组条件
order by 排序字段 asc|desc;

注意:分组后带有条件只能使用having, order by必须放到最后

你可能感兴趣的:(sql,数据库,mysql,ddl,dql,dml)