首页 > 技术文章 > sql必知必会

maoxianfei 2016-08-05 21:19 原文

注意:

sql不区分大小写

一.检索SELECT

检索单列
select pro_id
form products;
检索多列
select pro_id,pro_name,pro_price
form products;
检索所有列
select *
form products; 

二.排序数据order by (必须放在where 后面)

按单列排序
select pro_name
from products
order by pro_name;
按多列排序
select pro_name,pro_id,pro_price
from products
order by pro_price,pro_name;
按位置排序(select清单中的相对位置)
selcet pro_id,pro_price,pro_name
from products
order by 2,3;
指定排序方向(默认为升序asc,降序为desc)
select pro_id,pro_name,pro_price
from products
order by pro_price desc,pro_name

三.过滤数据where

检查单个值
select pro_name,pro_price
from products
where pro_price = 10;
不匹配检查
select vend_id,pro_name
from products
where vend_id != ‘Dl001’
范围值检查
select pro_price,pro_name
from products
where pro_price between 5 and 10;
空值检查(NULL)
select pro_name
from products
where pro_price is null;

操作符

= 等于 
!= <> 不等于 
< 小于 
<= 小于等于 
!< 不小于
> 大于
>= 大于等于
!> 不大于
between 在两个值之间
is null 为空值 
and 与
or 或
in 在
not 非
() 用括号表示优先级

四.高级数据过滤

 

使用and or ()操作符
select pro_name,pro_price
from products
where (vend_id ='dl001' or vend_id='bs001') and pro_price > 10;
使用 in 操作符
select pro_name,pro_price
from products
where vend_id in ('dl001','sa001')
order by pro_name;
使用not 操作符
select pro_name
from products
where not vend_id = 'dl001'
order by pro_name;

五.通配符过滤LIKE

使用百分号%匹配多个字符(acess使用*)
select pro_name,pro_id
from products
where pro_name like 'fish%'; 开头为fish的字符串
where pro_name like '%fish%'; 中间为fish
使用下划线 _ 匹配单个字符串
select pro_name,pro_id
from products
where pro_name like '_fish';
使用方括号[]
select cust_contact
from customers
where cust_contact like '[jm]%'
order by cust_contact;
取反 [^jm] ---access使用 [!jm]

六.创建计算字段

字段(filed)
拼接(concatenate)将值连结到一起构成单个值(使用+或||)
select vend_name + '('+vend_country+')'
///mysql 使用 select contact(vend_name,'(',vend_country,')')
from venders
order by vend_name; 
使用函数去除空格 rtrim() trim() ltrim()
select rtrim(vend_name) + '('+rtrim(vend_country)+')'
from venders
order by vend_name; 
使用别名
select rtrim(vend_name) + '('+rtrim(vend_country)+')' as vned_titile
from venders
order by vend_name; 
执行算术计算(+ - * /)
select pro_id,quantity,pro_price,quantity*pro_price as expanded_price
from products
where order_num = 2008;

七.使用数据处理函数

不同dbms相同函数功能使用函数不同

1.文本处理函数

文本处理函数
左边left()
长度length() len() datalenth()
小写lower()
右边right()
大写upper() ucase()--acess
发音soundex()
soundex()

select cust_name,cust_contact
from customers
where soundex(cust_contact)=soundex('micheal green');

2.日期时间处理函数(各种版本案例)

SQL server 和Sybase
select order_num from orders where datepart(yy,order_date)=2004;
Access
select order_num
from orders
where datepart(yyyy,order_date)=2004;
PostgreSQL
select order_num
from orders
where date_part(year,order_date)=2004;

3.数值处理函数

常用数值函数
abs() 绝对值
cos()
exp() 指数值
pi()
sin()
sqrt() 平方根
tan()

八.汇总数据

聚集函数 ---返回一列中单个值
avg()
count()
max()
min()
sum()
案例  
avg
select avg(pro_price) as avg_price
from products;

count
select count(*) as num_cust 所有行
from customers;
select count(cust_email) as num_cust 非空行
from customers;

distinct相同的值不计算
select avg(distinct pro_price) as avg_price
from products;

九.分组数据group by-having

分组数据
select vend_id,count(*) as num_prods
from products
group by vend_id;相同的id将合并为一组
hanving
select vend_id,count(*) as num_prods
from products
where pro_price >=4
group by vend_id
having count(*)>=2;
分组排序
select order_num,count(*) as items
from orders;
group by order_num
having count(*) >=3
order by items,order_num;

acess不能使用别名
order by count(*),order_num;
子句顺序
selsect 返回的表达列
from 检索数据表来源
where 行级过滤
group by 分组说明
having 组级过滤 
order by 排序

十.使用子查询

子句中只能用一个select语句
select cust_name,cust_contact
from customers
where cust_id in (select cust_id

          from ordersitems

          where order_num in (select order_num

                     from orderitems

                     where pro_id='rga001'));

  

十一.联结表

栗子
select vend_name,prod_name,prod_name
from vendors,products
where vendors.vend_id=products.vend_id;

十二.查创建高级联结

内部联结(等值联结)
selsect cust_name,cust_dontact
from customers as c,orders as o,orderitems as oi
where c.cust_id = o.cust_id
    and oi.order_num=o.order_num
    and pro_id='rhano1';

自联结

普通方法
select cust_id,cust_name,cust_contact
from customers
where cust_name=(select cust_name
          from customers
          where cust_contact='jim jones');
自然联结方法
select c1.cust_id,c1.cust_name,c1.cust_contact
from customers as c1,customers as c2
where c1.cust_name = c2.cust_name
    and c2.cust_contact = 'jim jones';
注意:otacle 中没有as 方法,使用时只需去掉as

自然联结

select c.* o.order_num, oorder_date,oi.pro_id,oi.quantity,oi.item_price
from customers as c,orders as o,orderitems as oi
where c.cust_id= o.cust_id
          and oi.order_num=o.order_num
          and pro-id='rgan01';


外部联结

内部联结
select customers.cust_id,orders.order_num
from customers,orders
where orders.cust_id =* customers.cust_id; 右边每行
where orders.cust_id *= customers.cust_id; 左边每行 

使用聚集函数

十三.组合查询union(union all-->显示所有包括重复的行)

unioin案例
select cust_name,cust-contact,cust_email
from customers
where cust_state in ('il','in','mi')
union
select cust_name,cust_contact,cust_email
from customers
where cust_name = 'funall';

十四.插入数据

插入一行(不安全)
插入新行到表,没有的值为null
insert into customers
values('1005','ss','dfds',null,null); 
插入一行(安全)
insert into customers(cust_id,cust_contact,cust_name)
values('2313',null,'sss');
从表导入到一个新表
insert into customers(cust_id,cust_contact,cust_email)
select cust_id,cust_contact,cust_email
from custnew;

复制表

(db2不支持)
select *
into custcopy
from customers;
mysql 和oracle
create table cystcopy as
select *
from customers;

十五.更新和删除数据update

更新特定行
update customers
set cust_email='sdsdf'
where cust_id='asd';
更新多行
update customers
set cust_email='sdsdf'
  cust_contact='ds'
where cust_id='asd';
更行所有行
删除行
delete from customers
where cust_id='2131';

十六.创建和操作表

creae table products
(pro_id char(10) not null,
vend_id char(10) not null,
pro_name decimal(8,2) not null,
pro_price integer not null default 1,
pro_desc varchar(100) null
);
使用默认值为日期
access now()
db2 current_date
mysql current_date()
oracle sysdate
postgreSQL current_date
sql sever getdate()
sybase getdate() 

更新表

增加行
alter tabel vendors
add vend_phone char(20); 
删除行
alter table vendors
drop column vend_phone;
删除表
drop table cust;

十七.使用视图(类似与函数功能)

创建
create view prodouctscustomers as 
select cust_name,cust_contact,pro_id
from customers,orders,orderitems
where customers.cust_id=orders.cust_id
and orderitems.order_num=orders.order_num;
使用
select cust_name,cust_contact
from productcustomers
where pro_id='rag';
删除
drop view viewname;

十八.使用存储过程execute

执行存储过程
execute addnewproduct('jts01','sd',6.0,'sdfsdf')
执行 存储过程名 传入参数
创建存储过程

create procedure maillinglistcount
--listcount参数从存储过程里返回一个数字
(listcount out number) 
is 
begin            
--存储过程开始
  select * from customers
  where not cust_email is null;
  listcount := sql%rowcount;
end;             
--存储过程结束

十九.管理事务处理(保证sql成批执行)

事务处理

SQL server
begin transaction
.....
commit transaction

MySQL
start transaction

PostgreSQL
begin;

回退rollback

delete insert update 

保留点

MySQL oracle
--保留点
savepoint delete1;
--回退
rollback to delete1;

sql server 和Sybase
save transaction delete1;
rollback transaction delete1;

二十.使用游标

对检索出来的数据浏览

创建游标declare cursor

创建
使用游标open cursor

关闭游标close cursor

二十一.SQL高级特性

约束:管理插入处理数据库的规则

主键(primary key)

外键

索引

触发器

推荐阅读