`
runfeel
  • 浏览: 907621 次
文章分类
社区版块
存档分类
最新评论

SQL从入门到精通

 
阅读更多

无论你是初学数据库的新手,还是许久没接触SQL语句的程序员,亦或是即将面临一场关于数据库的考试的孩子,这十条SQL都将让你受益终生,让你一步一步逐渐将SQL融会贯通。很多数据库的书讲到SQL查询语句时总是让人难以看懂,条理性极差,故本人通过我的学习经历整理了这最经典最重要而且清晰易懂的SQL语句,同时它们也是从难到易排序的。学好这些语句,让你在SQL上从菜鸟变雄鹰~~~~~


我们使用这四张经典的表:

CUSTOMERS:cid,cname,city,discnt(折扣)

AGENTS:aid,aname,city,percent(佣金百分比)

ORDERS:ordno,month,cid,aid,pid,qty(订购商品数量),dollars(商品总价)

PRODUCTS:pid,pname,city,quatity,price


1.最简单的查询订货记录中所有零件的 pid

select distinct pid from orders ;


2.有查询条件的查询顾客cid=c05订购的货物pid

select distinct pid from orders where cid='5' ;


3.连接:(1)定了货物 p01的顾客名字

select pname from CUSTOMERS,Orders

where CUSTOMERS.cid = Orders.cid and Orders.pid = 'p01' ;

再来一个两次连接的(3个表):

(2)通过名字为‘寡人无疾’的代理商订货的顾客姓名

select cname from CUSTOMERS,Orders,AGENTS

where CUSTOMERS.cid = ORDERS.cid and ORDERS.aid = AGENTS.aid

and AGENTS.name = '寡人无疾' ;


4.别名:至少被两个人订购了的产品pid:

select distinct o1.pid from ORDERS o1, ORDERS o2

where o1.pid=o2.pid and o1.pid<o2.pid;

如果没有o1.pid<o2.pid 则会每个产品出现两次噢


5.量化查询:佣金百分率最小的代理商aid:

select aid from AGENTS

where percent <=all(select percent from AGENTS);


6.集合函数查询:(1)产量 p03 的订购总量:

select sun(qty) as total from ORDERS where pid = 'p03' ;

注:as total意思是用了sun函数得到结果显示在total这个新的列上

(2)顾客居住的城市数量

select count(city) from CUSTOMERS;

注:这句话查询出的城市是包括重复的城市名的


7.子查询,in:订购了被代理商 a06 订购过的产品的顾客 cid :

select distinct cid from ORDERS

where pid in (select pid from Orders where aid = 'a06') ;

释:selec查询的结果可以作为集合放入另外的select语句


8.exists,in,连接,=any四种方法的等价形式:订购了产品 p01 的顾客所在city

连接: select distinct city from CUSTOMERS c,ORDERS o

where o.cid = c.cid and o.pid = 'p01' ;

in: select distinct city from CUSTOMERS

where cid in (select cid from ORDERS where pid = 'p01') ;

exists: select distinct city from CUSTOMERS c

where exists (select * from ORDERS where cid = c.cid and pid = 'p01')

=any:select distinct city from CUSTOMERS

where cid = any (select cid from ORDERS where pid = 'p01') ;

注:因为exists正向查询不是必须的而且容易出错,故不专门介绍了(但是not exists有时确实必要的)


9.having:被某代理商订购量超过1000的某种商品的pid和aid以及总量

select pid,aid,sun(qty) as total from ORDERS

group by pid,aid

having sun(qty)>1000 ;

注:group by 是按什么排序的意思,having则允许在选择条件里使用集合函数值作为条件。另外记得如果要用having语句必须有group by 噢。


10.双重否定(not exists):所有顾客都订购过的产品的编号(pid):

select pid from ORDERS

where not exists(

select* fromPRODUCTS

where not exists(

selectpid fromORDERSwhere pid = PORUCTS.pid

)

) ;

此句意思是:不会有 有顾客没买的的商品 存在

exists的意思是在此范围中或者说存在这样的情况; not exists就是不在这个范围的意思

condition1:这个商品不会condition2。
condition2:有客户没有购买的商品。

这句怎么好像有问题呢,求大神帮改改(*^__^*)

好了,不管怎么说,十条SQL看完有没有觉得自己一下懂SQL啦?

有的话顶一个噢(*^__^*)

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics