sql语言是结构化的查询语言(Structured Query Language),可以分为四类:数据定义语言(DDL),数据操纵语言(DML),事务控制语言(TCL)和数据控制语言(DCL)。其中DDL是用于改变数据库对象结构,DML用于操纵数据。这里列举一些DDL和DML中的简单sql语句。
1、创建表
create table 表名(
字段名 数据类型 约束,
字段名 数据类型 约束,
…
例如:
create table tb_user(
id int primary key auto_increment,
name varchar(50) not null,
sex char(1) not null,
age int default 18,
birthday date
foreign key (id)references tb_custom(id)
)
其中约束有几种类型:
i 非空约束 not NULL
ii 默认约束 DEFAULT
iii 主键约束 primary key
iv 外键约束 foreign KEY
v 自增长约束 auto_increment
2、对字段进行操作
i 增加字段
alter table 表名 add 字段名 数据类型;
ii 删减字段
alter table 表名 drop column 列名;
iii 修改字段
alter table 表名 modify column 列名 数据类型;
3、对数据进行操作
i 插入数据
insert into 表名(字段名,字段名…) values(数据,数据…);
ii 删除数据
delete from 表名 where 条件;
iii 修改数据
update 表名 set 字段名=数据,字段名=数据… where 条件;
4、删除表
drop table 表名;
5、添加外键
alter table 表名 add foreign key (外键字段) references 主表 (主键);
6、创建表时 创建索引
create table tb_test1(
id int primary key, – 创建主键索引
tname varchar(50),
age int,
email varchar(50) unique,
index(tname), – 创建普通索引
unique index(email) – 唯一索引
)
7、如果表已创建,也可以增加索引
create 索引类型 index 索引名称 on 表名(字段名…)
alter table 表名 add index 索引名(属性)
8、 删除索引
drop index 索引名 on 表名;
9、创建视图
create view 视图名 AS
select语句
10、 删除视图
drop view 视图名
11、查询语句
select 字段名 from 表名 where 条件;
12、子查询
select 字段名 from 表名 where (select语句)
或 select 字段名 from (select语句)
13、关联查询
i 内连接
select 字段名 from 表1 inner join 表2 on 表1.字段=表2.字段
或
select 字段名 from 表1,表2 where 表1.字段=表2.字段
ii 外连接
a) 左外连接
select * from 表1 left join 表2 on 表1.字段=表2.字段
b) 右外连接
select * FROM 表1 right join 表2 on 表1.字段=表2.字段