数据库入门之SQL基础总结

1 创建一个数据库
CREATE DATABASE databasename
2 删除一个数据库
drop database dbname
3 创建新表
create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..)
4 删除表
DROP TABLE tablename
5 增加列
Alter table tabname add column col type

列增加后将不能删除

6 添加主键
Alter table tabname add primary key(col)
7 删除主键
Alter table tabname drop primary key(col)
8 创建索引
create [unique] index idxname on tabname(col….)
9 删除索引
drop index idxname

索引是不可更改的,想更改必须删除重新建

10 创建视图
create view viewname as select statement
11 删除视图
drop view viewname
12 在范围内选择
select * from table1 where 范围
13 插入
insert into table1(field1,field2) values(value1,value2)
14 删除
delete from table1 where 范围
15 更新
update table1 set field1=value1 where 范围
16 like的用法
select * from table1 where field1 like%value1%
17 order by的用法(排序)
select * from table1 order by field1,field2 [desc]
18 求总数
select count as totalcount from table1
19 求和
select sum(field1) as sumvalue from table1
20 求平均值
select avg(field1) as avgvalue from table1
21 求最大值
select max(field1) as maxvalue from table1
22 求最小值
select min(field1) as minvalue from table1
23 左连接
select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c

左连接结果集包括连接表的匹配行,也包括左连接表的所有行

24 子查询
select a,b,c from a where a IN (select d from b )
25 between的使用方法
select * from table1 where time between time1 and time2

between限制查询数据范围时包括了边界值

26 in的使用方法
select * from table1 where a [not] in (‘值1,’值2,’值4,’值6)
27 两张关联表,删除主表中已经在副表中没有的信息
delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 )

参考:经典SQL语句大全(绝对的经典)

你可能感兴趣的:(数据库)