SQL学习——(二)高级语句
(1)Top:
SQLsever:select top 3/50 percent */列i/列i,...,列j from 表a;
Mysql:select */列i/列i,...,列j from 表a limit 3;
Oracal:select */列i/列i,...,列j from 表a where Rownum < 3;
(2)like:
select * from 表a where 列i like "N%"
(3)通配符
% 包含一个或者多个
-包含一个
[**]在[]中的任一字符
[!**]在[]中字符中的任一字符
(4)in:
select * from 表a where 列i in (值i,…,值j);
(5)between and:
select * from 表a where 列i bfetween A(包含)and B(不包含);
(6)join和key:适用于多表之间的操作,主键(无重复);
select 表a.列1,表a.列2,表b.列1,表b.列2,表b.列3 from 表a,表b where 表1.主key=表a.主key;
① 内连接inner join:
select 表a.列1,表a.列2,表b.列1,表b.列2,表b.列3 from 表a inner join 表b on 表1.主key=表a.主key order by 表1.列i;
② 左连接left join:
select 表a.列1,表a.列2,表b.列1,表b.列2,表b.列3 from 表a left join 表b on 表1.主key=表a.主key order by 表1.列i;
③ 右连接right join:
select 表a.列1,表a.列2,表b.列1,表b.列2,表b.列3 from 表a right join 表b on 表1.主key=表a.主key order by 表1.列i;
④ 全连接full join:
select 表a.列1,表a.列2,表b.列1,表b.列2,表b.列3 from 表a full join 表b on 表1.主key=表a.主key order by 表1.列i;
(7)union:连接两个select,不重复;union all 重复
select 列i from 表a
union
select 列j from 表b;
select 列i from 表a
union all
select 列j from 表b;
(8)select into 创建表的备份附件,文档
select 列/* into new表 from old表;
select 列/* into 表名 in ‘数据库名' from 表名;
eg:从A、B两表取部分信息组合成新表C:
select 表A.列i ,表B.列j into 表C from 表A inner join 表B on A.id=B.id;
(9)SQL约束
① not null:创建表时主键不为空:
create table 表a
(id int not null,
...
)
② unique:约束唯一标识列:
Ⅰ:创建一列:
create table 表a
(id int not null unique,
...
)
Ⅱ:创建多列:
create table 表a
(id int not null ,
age int,
...
constraint uc_PersinID unique(id,age),
)
Ⅲ:若表已存在情况下,用add,drop做更改删除;
alter table 表a
add/drop uc_PersinID unique(id,age);
③ primary key 标识主键
create table 表a
(id int not null primary key,
...
)
若表已存在情况下,用add,drop做更改删除;
alter table 表a
add/drop primary key(id);
④ foregin key
⑤ check限制列的范围
create table 表a
(id int not null check(id>0),
...
)
若表已存在情况下,用add,drop做更改删除;
alter table 表a
add/drop check(id>0);
⑥ default:约束用于向列中插入默认值:
create table 表a
(id int not null ,
city varchar(255) default 'Sadnes',
...
)
若表已存在情况下,用add,drop做更改删除;
alter city set/drop default 'Sadnes';