未免遗忘sql语句的基本使用,总结一下:
1.基本增删改查
insert into p_info (name,age) values('cc',24);
delete from p_info where id = 8;
update p_info set name = 'ip' where id = 5;
select * from p_info;
2.多表查询
(1)自然连接(等值连接,将记录相同的提取出来,包括ID)
select * from company1 natural joincompany2;
(2)交叉连接(笛卡尔算法) 此句为ID相同的连接起来
select * from company1 c1,company2 c2 wherec1.id = c2.id;
(3)内连接(也是ID相同的连接起来,不过显然效率更高)
select * from company1 c1 inner joincompany2 c2 on c1.id = c2.id;
(4)外连接
左外连接 c1在左侧,且左表全部显示,右表只有ID相同的部分才会显示
select * from company1 c1 left joincompany2 c2 on c1.id = c2.id;
右外连接 c1表在右侧,且右表全部显示,左表只有ID相同的部分才会显示
select * from company1 c1 right joincompany2 c2 on c1.id = c2.id;
(5)自连接 连接的表示是同一个表只有别名不同
select * from company1 c1,company1 c2 wherec1.id=c2.id;
3.子表查询
(1)all大于 work=find 中最大的ID所有记录
select * from company2 where id > all(
selectid from company2 where work = 'find'
);
(2)exists 存在如果子语句存在就查询所有记录
select * from company2 where exists(
selectname from company2 where work = 'find'
);
(3)not exists 不存在
4.集合与视图
(1)集合 使用集合时要保证字段一样
将重复的记录过滤了,合并后无重复记录 是内容重复而不包括ID
select * from company1 union select * fromcompany2;
(2)视图
create view union_view as select * fromcompany2 where id>3;
-- 创建语句执行后视图 union_view就存在了
-- 然后可以此表为新表查询想要的记录
-- 视图不可更改,只可查询
下面是自连接的一个网上的小例子:
Name | bumen | zhiwu |
张三 | 市场 | 员工 |
李四 | 销售 | 经理 |
王五 | 市场 | 经理 |
赵六 | 销售 | 员工 |
-- 利用自连接的方式查询出员工所在部门的经理姓名
select w1.name,w1.bumen,w2.name manager_name fromworker w1 ,worker w2 where w1.bumen = w2.bumen and w2.zhiwu='经理';