记录的都是本身平时不知道的:sql
一 基础索引
1 根据已有表建立新表io
a create table_new like table_old;table
b create table_new as select col1,col2,......from table_old defination only;基础
2 增长一个列date
alter table table_name add column col typefile
列增长后不能删除,DB2中列加上后数据类型也不能该表,惟一能改变的是增长varchar类型的长度
select
3 增长主键 alter table table_name add primary key(col);
sql语句
删除主键 alter table tabe_name drop primary key(col);技巧
4 建立索引 create [unique] index index_name on table_name(col,......);
删除索引 drop index index_name;
索引是不可更改的,要想更改必须删除后从新建
5 建立视图 create view view_name as select statement
删除视图 drop view view_name
6 几个简单的sql语句
插入 insert into table_name(field1,field2) values(value1,value2);
删除 delete from table where......
更新 update table_name set field1 = value1 where....
查找 select * from table_name where field1 like "%value1%"
总数 select count totalcount from table_name
求和 平均 最大 最小 select sum/avg/max/min(field1) as newvalue from table_name
7 几个高级查询运算词
union
union运算符经过组合其余两个结果表(例如table1和table2)并消去表中任何重复行而派生出的一个新的结果表,当all随union一块儿使用时(即union all),不消除重复行,两种状况下,派生表的每一行不是来自table1就是来自table2
except
except运算符经过包括全部在table1中可是不在table2中的行并消除全部重复行而派生出一个结果表,当all随except一块儿使用时(except all),不消除重复行。
intersect
intersect运算符经过只包括table1和table2都有的行并消除并消除全部重复行而派生出一个结果表,当all随intersect一块儿使用时,不消除重复行。
注:使用运算符的几个查询结果行必须是一致的。
8 外链接
left (outer) join 左外链接(左联接):结果集包括链接表的匹配行,也包括左联接表的全部行。
right (outer) join 右外链接(右链接):结果集包括链接表的匹配行,也包括右链接表的全部行。
full/cross (outer)join:全外链接:不只包括符号链接表的匹配行,还包括两个链接表中的全部记录。
二 提高
1 复制表(只复制表结构,源表名:a, 新表名:b)
法1:select * into b from a where 1<>1 (仅适用于SqlServer)
法2:select top 0 into b from a
2 拷贝表(拷贝数据,源表名:a,新表名:b)
insert into b(filed1,field2,field3) select field1.field2,field3 from a
3 子查询(表名1;a,表名2:b)
select field1,field2,field3 from a where field in (select field4 from b)
4 between
between限制查询数据范围时包括了边界值,not between不包括
5 in的使用方法
select * from table_name where a [not] in ("值1","值2","值3");
6 两张关联表,删除主表中已经在副表中没有的信息(主表:table1;副表:table2)
delte from table1 where not exists(select * from table2 where table1.field1 = table2.field1)
7 前10条记录
select top 10 from table_name where......
三 技巧
1 1-1 ,1=2的使用,在sql语句组合时用的较多
“where 1=1 ” 表示选择所有,“where 1=2” 表示所有不选