#26 包含JOIN遗忘的行
来源:互联网 发布:mac电脑中病毒怎么杀毒 编辑:程序博客网 时间:2024/06/06 22:27
- --包含JOIN遗忘的行
- select getdate() --2009-01-05 22:54:33.763 in 西安 by 陈亮
- /*--生成数据
- use tempdb
- IF object_id('customer') is not NULL
- drop table customer
- Go
- Create table customer (id int ,name varchar(20))
- Go
- insert into customer
- select 1,'Bety' UNION ALL
- select 2,'Robert' UNION ALL
- select 3,'Janette'
- --
- IF object_id('invoice') is not NULL
- drop table invoice
- Go
- Create table invoice (id int ,whn datetime,Custid int ,cost int)
- Go
- insert into invoice
- select 1,'2009-01-01',1,100 UNION ALL
- select 2,'2009-01-02',1,500 UNION ALL
- select 3,'2009-01-05',3,200
- --*/
- --默认情况下,JOIN就是INNER JOIN。 它将仅仅给出同时匹配两个表的数据行:
- select *
- from customer INNER JOIN invoice
- on (customer.id=custid);
- /*
- id name id whn Custid cost
- 1 Bety 1 2009-01-01 00:00:00.000 1 100
- 1 Bety 2 2009-01-02 00:00:00.000 1 500
- 3 Janette 3 2009-01-05 00:00:00.000 3 200
- */
- --与此相反,LEFT OUTER JOIN 将包括左表中的所有行——即使有的行不匹配右侧表的任意行业是如此:
- select *
- from customer LEFT OUTER JOIN invoice
- on (customer.id=custid);
- /*
- id name id whn Custid cost
- 1 Bety 1 2009-01-01 00:00:00.000 1 100
- 1 Bety 2 2009-01-02 00:00:00.000 1 500
- 2 Robert NULL NULL NULL NULL
- 3 Janette 3 2009-01-05 00:00:00.000 3 200
- */
- --能够使用短语LEFT JOIN 取代 LEFT OUTER JOIN 。单词OUTER是个可选词汇。
- --类似地,如果你在使用内连接,那么可以通过使用INNER JOIN 来取代JOIN 来明确说明连接类型。这点要求在Access中是强制性的。
- --过滤必须在连接条件(ON子句)中完成。在SQL中,首先执行JOIN子句,然后应用WHERE条件。
- --如果想得到Robbert的数量0,那么需要使用LEFT OUTER JOIN ,这样,左表(customer)的每一行都出现在结果中:
- select [name] ,count(custid)
- from customer LEFT JOIN invoice on (customer.id=custid)
- group by name
- /*
- name count(custid)
- Bety 2
- Janette 1
- Robert 0
- */
- --注意
- select [name] ,count(*)
- from customer LEFT JOIN invoice on (customer.id=custid)
- group by name
- /*
- name count(*)
- Bety 2
- Janette 1
- Robert 1
- */
- select [name] ,count(name)
- from customer LEFT JOIN invoice on (customer.id=custid)
- group by name
- /*
- name count(name)
- Bety 2
- Janette 1
- Robert 1
- */
- --使用UNION也可以解决问题,编写第二个查询,它对不在invoice中的客户返回0:
- select [name] ,count(*)
- from customer JOIN invoice on (customer.id=custid)
- group by name
- UNION
- select name ,0
- from customer a
- where not exists (select * from invoice b where b.custid=a.id)
- --END*/
- #26 包含JOIN遗忘的行
- 被遗忘的java
- 被遗忘的Rotor
- 被人遗忘的
- 被遗忘的BLOG
- 未曾遗忘的凝视
- 被遗忘的时光
- 被遗忘的世界
- 遗忘掉的昨天
- 遗忘的梦想-游戏
- 遗忘的角落
- 遗忘了的昨天
- 未曾遗忘的梦想
- 一些遗忘的东西
- 容易遗忘的事
- 快遗忘的东西
- 遗忘的Statement对象
- 回忆遗忘的js
- Hibernate QBC查询基本语句
- 需求随想
- Informatica Power Center Server 在 Vista 中不可见
- Struts标签问题:Attribute id invalid for tag form according to TLD
- 侠诺VPN顺天府连锁超市应用案例
- #26 包含JOIN遗忘的行
- 将文件秘密隐藏在图片中
- 面向对象与UML学习笔记
- 六个关键问题让你了解该用哪一种VPN
- iText生成PDF
- eDonkey (eD2k) vs. BitTorrent (BT)
- 论项目管控浅见(一):单打独斗篇
- vc防止运行多个程序,重复运行,同一个程序
- Google map api key