| 根据已有的表创建新表 |
create table tab_new like tab_old
create table tab_new as select col1,col2… from tab_old definition only
|
|
| 添加或者删除主键 |
Alter table tabname add primary key(col)
Alter table tabname drop primary key(col)
|
|
| 创建&删除索引 |
create [unique] index idxname on tabname(col….)
drop index idxname
|
注:索引是不可更改的,想更改必须删除重新建。
|
| 增删改查 |
select * from table1 where
select * from table1 where field1 like ’%value1%’
select * from table1 order by field1,field2 [desc]
select count as totalcount from table1
select sum(field1) as sumvalue from table1
insert into table1(field1,field2) values(value1,value2)
delete from table1 where
update table1 set field1=value1 where
|
|
| Union |
|
UNION 运算符通过组合其他两个结果表(例如 TABLE1 和 TABLE2)并消去表中任何重复行而派生出一个结果表。当 ALL 随 UNION一起使用时(即 UNION ALL),不消除重复行。两种情况下,派生表的每一行不是来自 TABLE1 就是来自 TABLE2。
|
| Except |
|
EXCEPT 运算符通过包括所有在 TABLE1 中但不在 TABLE2 中的行并消除所有重复行而派生出一个结果表。当 ALL 随 EXCEPT 一起使用时 (EXCEPT ALL),不消除重复行。
|
| INTERSECT |
|
INTERSECT 运算符通过只包括 TABLE1 和 TABLE2 中都有的行并消除所有重复行而派生出一个结果表。当 ALL 随 INTERSECT 一起使用时 (INTERSECT ALL),不消除重复行。 |
| left (outer) join |
select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c
select a.a, a.b, a.c, b.c, b.d, b.f from a LEFT OUT JOIN b ON a.a = b.c
|
左外连接(左连接):结果集几包括连接表的匹配行,也包括左连接表的所有行。右外连接(右连接):结果集既包括连接表的匹配连接行,也包括右连接表的所有行。全外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录。
|
| 复制表 |
select * into b from a where 1<>1(仅用于SQlServer)
select top 0 * into b from a
|
只复制结构,源表名:a 新表名:b |
| 拷贝表 |
insert into b(a, b, c) select d,e,f from b; |
拷贝数据,源表名:a 目标表名:b |
| in |
select * from table1 where a [not] in (‘值1’,’值2’,’值4’,’值6’) |
|
| 数据库分页 |
|
|
| 按姓氏笔画排序 |
Select * From TableName Order By CustomerName Collate Chinese_PRC_Stroke_ci_as //从少到多 |
|
| 开头到N条记录 |
Select Top N * From 表 |
|
| N到M条记录(要有主索引ID) |
Select Top M-N * From 表 Where ID in (Select Top M ID From 表) Order by ID Desc
select top 10 recid from A where recid not in(select top 30 recid from A)
|
第二个sql语句在某种情况下可能会造成读到的数据不是预想得到的数据 |
| N到结尾记录 |
Select Top N * From 表 Order by ID Desc |
|
| |
|
|
| |
|
|
| |
|
|