RSS

Left [Outer] Join , Right [Outer] Join, Inner Join and Full Join

11 Feb

Table1

Table2

id

name

id

Score

1

Nathaniel

1

90

2

Finchan

2

100

4

Jean

3

70

连接查询包括:

一、外连接

1.概念:包括左向外联接、右向外联接或完整外部联接

2.左连接:left [outer] join (1)左向外联接的结果集包括 LEFT OUTER 子句中指定的左表的所有行,而不仅仅是联接列所匹配的行。如果左表的某行在右表中没有匹配行,则在相关联的结果集行中右表的所有选择列表列均为空值(null) (2)SQL语句: select * from table1 left [outer] join table2 on table1.id=table2.id
3.右连接:right join right outer join (1)右向外联接是左向外联接的反向联接。将返回右表的所有行。如果右表的某行在左表中没有匹配行,则将为左表返回空值。 (2)SQL语句: select * from table1 right [outer] join table2 on table1.id=table2.id

4.完整外部联接:full [outer] join (Mysql不支持) (1)完整外部联接返回左表和右表中的所有行。当某行在另一个表中没有匹配行时,则另一个表的选择列表列包含空值。如果表之间有匹配行,则整个结果集行包含基表的数据值。 (2)SQL语句: select * from table1 full join table2 on table1.id=table2.id 对于不实现full join的数据库可以这样实现: select * from table1 left outer join table2 on table1.id = table2.id union select * from table1 right outer join table2 on table1.id=table2.id

二、内连接
1.概念:内联接是用比较运算符比较要联接列的值的联接
2.
内连接:[inner] join
3. SQL
语句:
select * from table1 join table2 on table1.id=table2.id

4.等价(与下列执行效果相同) A:select a.*,b.* from table1 a,table2 b where a.id=b.id B:select * from table1 cross join table2 where table1.id=table2.id (注:cross join后加条件只能用where,不能用on)

三、交叉连接(完全)

1.概念:没有 WHERE 子句的交叉联接将产生联接所涉及的表的笛卡尔积。第一个表的行数乘以第二个表的行数等于笛卡尔积结果集的大小。(table1table2交叉连接产生3*3=9条记录)
2.
交叉连接:cross join (不带条件where…)
3. SQL
语句: select * from table1 cross join table2

4.等价(与下列执行效果相同) A:select * from table1,table2

Other Examples: 1) SELECT a.au_fname, a.au_lname, p.pub_name FROM authors a LEFT OUTER JOIN publishers p ON a.city = p.city ORDER BY p.pub_name ASC, a.au_lname ASC, a.au_fname ASC 2) SELECT s.stor_id, s.qty, t.title FROM sales s RIGHT OUTER JOIN titles t ON s.title_id = t.title_id AND s.qty > 50 ORDER BY s.stor_id ASC

3) Insert INTO cttag(articleid,classid,nclassid) Select a.articleid,a.classid,a.nclassid from ctarticle a left join cttag b on a.articleid=b.articleid where b.articleid is null

Advertisements
 
Leave a comment

Posted by on 02/11/2010 in MYSQL

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

 
%d bloggers like this: