数据库基础のLeft Jion,Right Jion,Inner Jion,联合查询

 

CREATE TABLE testA
aID int( 1 ) AUTO_INCREMENT PRIMARY KEY ,
aNum char( 20 )
)
CREATE TABLE testB(
bID int( 1 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
bName char( 20 )
) 

表testA记录如下:
aID aNum
1   a11
2   a22
3   a33
4   a44
5   a55

表testB记录如下:
bID bName
1   b11
2   b22
3   b33
4   b44
8   b88 

   

1.left join(左联接)

sql语句如下:
SELECT * FROM testA LEFT JOIN testB ON testA.aID = testB.bID

结果如下:
aID aNum bID bName
1   a11  1    b11
2   a22  2    b22
3   a33  3    b33
4   a44  4    b44
5   a55  NULL NULL

left join是以A表的记录为基础的,testA可以看成左表,testB可以看成右表,左表(testA)的记录将会全部表示出来,而右表(testB)只会显示符合搜索条件的记录(例子中为: testA.aID = testB.bID). testB表记录不足的地方均为NULL.

 

 2.right join(右联接)

sql语句如下:
SELECT * FROM testA RIGHT JOING testB ON testA.aID = testB.bID

结果如下:
aID aNum bID bName
1    a11  1   b11
2    a22  2   b22 
3    a33  3   b33 
4    a44  4   b44 
NULL NULL 8   b88

仔细观察一下,就会发现,和left join的结果刚好相反,这次是以右表(testB)为基础的,testA表不足的地方用NULL填充.

 

3.inner join(相等联接或内联接)

sql语句如下:
SELECT * FROM testA INNER JOIN testB ON testA.aID = testB.bID

等同于以下SQL句:
SELECT * FROM testA,testB WHERE testA.aID = testB.bID

结果如下:
aID aNum bID bName
1    a11  1   b11         
2    a22  2   b22        
3    a33  3   b33        
4    a44  4   b44         

 很明显,这里只显示出了 testA.aID = testB.bID的记录.这说明inner join它只显示符合条件的记录.

 

 

你可能感兴趣的:(联合查询,详解,inner,left,right,jion,jion,jion)