sql命令集锦

sql简单语句:
select a,b
from table1,table2
where table1.id=table2.id;

等价于
select a,b
from table1 natural join table2;
//这是自然连接,是两个表的共同属性相同的取值一样的结果

select a1,a2,a3
from r1,r2,r3//这是笛卡尔积

select a1,a2,a3
from r1 natual join r2,r3
where r1.id =r3.id //先运算join 在运算笛卡尔积

//如果三者有并且只有id相同,那么   
select a1,a2,a3
from r1 natual join r2 natual join r3;//可以看做三者的自然连接


//自然连接会自动忽略没有相同属性的元祖,这样的话就需要外连接

//如果r1,r3有ID但是r2没有ID这样就会丢失所有的内容
select a1,a2,a3
from r1 join r2 using(id);//指定属性自然连接


3.4 附加的基本运算
更名运算

select a1
from r1,r2
where r1.id=r2.id;
等价于
select a1
from  r1 as S,r2 as T
where S.id=T.id;//as是一个重命名的方法

//在sql的标准里面,是对大小写敏感的,但是在sql数据库里面 却不敏感
 
4.2排列元素:
select q
from r1 order by q asc (desc);//按照升序和降序排列

集合运算
并运算union  :
(select a1 from r1)
union (select a2 from r2);//union运算自动去除重复

(select a1 from r1)
union all(select a2 from r2);//union all 能够保留所有的重复

交运算
(select a1 from r1)
insect (select a2 from r2);//insect运算自动去除重复

(select a1 from r1)
insect all(select a2 from r2);//insect all 能够保留所有的重复

差运算

(select a1 from r1)
except (select a2 from r2);//except 运算自动去除重复

(select a1 from r1)
except all(select a2 from r2);//except all 能够保留所有的重复

空值:

select a1
from r1
where id=null;

and :
true and unknow 是unknown
unknown and false 是false
unknown and unknow 是unknown 

or 
 ture and unknown  是true
 false and unknow 是unknown
 unknown and unknown 是unknown

not unknown 是unknown 

true> unknown >false;//这是他们三个的优先级区别

如果where 对一个元组计算出unknown 或者 false  则不能加入到结果里面

null=null返回的是unknown  而不是true  

聚集函数
类似于avg sum min max count的函数
分组聚集 ground by  如果有分组  那个分组是执行的第一步

having子句(在形成分组后才会起作用):不满足having的分组将被抛弃,select查询  查询的是抛弃过的分组

集合成员资格 in 和 not in:查询的是是否在集合中
where  .. and .. and id in (select  id from r1);//一个in和not in 的简单应用

集合的比较

比如  where salary > (select salary from  r1);//这句话的意思是salary 是否比子查询的某一个salary高,查询的是某一个

空关系测试(查询一个集合中是不是存在元组)
where exists (select * from r1);

重复元组存在性测试:
where  unique (select * from r1);//是否存在重复的元组。

子查询是一个集合  可以用在from后面
例如: select *from (select id from r1);//返回的是r1中的所有的id

标量子查询(子查询只返回一个元组):
select * from r2 where(select count(*)from r1);//count 只返回一个数字,这也就是一个元组,标量子查询不能当做集合使用。

数据库的修改:
delete 只能作用于一个关系 删除的是表的内容;
delete from r1 where p;//删除的是使p为真的内容
delete from r1;//删除的是整个表(内容,表依然存在)。

插入 
insert into r1 values(,.....);//按照属性顺序插入
insert into r1(.....)values(,.,.,.);//按照(..)插入值
还可以插入一个集合:
insert into  r1 select a1,a2,a3,a4 where p>100;//选择的基础上插入值(在执行插入动作之前是先执行查询表的)
insert  into r1 select * from r1;//体现的先执行的是查询,查询结束之后才进行插入

更新:更新也可以基于查询的基础上::
update r1 set a1=100 where a1>91;//update 的动作也是面对关系的,不是关系的动作不行。

猜你喜欢

转载自blog.csdn.net/xizi_ghq/article/details/88831547