77家的会客2010

sql之join用法完全版
Weather:阴转中雨,东南风5-6级转南风5-6级,(21~26)℃

一、各种JOIN的含义

SQL中大概有这么几种JOIN:

cross join

inner join

left outer join

right outer join

full outer join

 

首先都是基于cross join(笛卡尔乘积),然后是inner join,在笛卡尔乘积的结果集中去掉不符合连接条件的行。

left outer join 是在inner join的结果集上加上左表中没被选上的行,行的右表部分每个字段都用NUll填充。

right outer join 是在inner join的结果集上加上右表中没被选上的行,行的左表部分全用NULL填充。

outer的意思就是"没有关联上的行"。

 

二、旧式写法和标准写法:

 

1、INNER Join code as the following:

 

Select * from A a, B b where a.categoryID = b.categoryID;

Equals:

Select * from A a inner join B b on a.categoryID = b.categoryID;

 

2、OUTER Join code as the following

 

select * from A a full(left/right) outer join B b on a on a.categoryID = b.categoryID;

Equals::

Select * from A a, B b where a.categoryID *= b.categoryID;

Select * from A a, B b where a.categoryID =* b.categoryID;

 

三、例子

Table A have 12( 8+4) entries, 8 entries have valid relation with B

Table B have 80(77+3) entries , 77 entries have valid relation with A.

 

then the return amount of join is :

cross join : 12*80

inner join : 77

full outer join : 77+4+3

left outer join: 77 + 4

right outrer join: 77 + 3

(07/24) 本本秀
加奥运班 (08/08)

[sql之join用法完全版]的回复

大雾 于 2008-08-06 11:35:35 发表 | IP:123.120.209.*

看不懂的飘过。。。。。

柠檬园主 于 2008-08-06 19:08:13 发表 | IP:221.201.145.*

天上飘的,水里潜的...呵呵

littllenew 于 2008-08-27 11:38:45 发表 | IP:218.18.28.*

问你一个sql语句的问题。

select  * from (select c.classname,(select count(id) from news n where n.bsjg=c.id) as t from class_web c where c.preid=130) m order by m.t desc

class_web主要结构:

id       className

news主要结构:

id      bsjg

问题:我只要前10条数据,但只要一加入top 10 就会出现第二条数据以后与第一条数据相同的情况。但不加top 10时,数据是正常的。但必须要前10条比较多的类别与count后的数目。

(问题说白了就是:从新闻类别里选出这个新闻类别的新闻的条目,并按条目排序。)

期待结果:

classname                          t

香港                                  3

台湾                                  2

美国                                  1

其它                                   0

4#   littllenew 于 2008-08-27 17:29:18 发表 | IP:218.18.28.*

我使用 的还是比较低级的access数据库呢。太高级的数据库又不想学。

有access版本 吗??

5#   柠檬园主 于 2008-08-27 23:12:53 发表 | IP:124.93.19.*

SELECT A.Z1RKCD,COUNT(*) AS CNT FROM FBN11P A,CMSHNP B
 WHERE A.Z1SBSB=B.I1SNCD GROUP BY Z1RKCD ORDER BY CNT DESC
 FETCH FIRST 10 ROWS ONLY

这个是在DB2下跑的,SYBASE下可以用以在SELECT前加SET ROWCOUNT 10来限制前10条.但在MSSQL下应该是没这两种用法.这样的话,就得用row_number() over()等来构造IDENTIFY然后才能再在外层用SELECT TOP N

6#   littllenew 于 2008-08-28 09:13:38 发表 | IP:218.18.128.*

汗,这么复杂。还是i++来判断吧。反正类别不超过100个。

7#   柠檬园主 于 2008-08-28 09:57:04 发表 | IP:221.201.145.*

也是,反正取出来的东西不多,你就循环10次取出来前10个就行了。

Post a Comment~