1. 程式人生 > >【mysql】mysql的內連線和外連線小例子

【mysql】mysql的內連線和外連線小例子

解釋名詞:

1、內連線(自然連線): 只有兩個表相匹配的行才能在結果集中出現

2、外連線: 包括

(1)左外連線(左邊的表不加限制)

(2)右外連線(右邊的表不加限制)

(3)全外連線(左右兩表都不加限制)

3、建立student、score表如下

                                           (student表)


                                     (score表)

A:內連線sql
         select st.student_name,sc.object,sc.score,st.student_class
         from student st ,score sc where st.student_id=sc.student_id

        執行結果:

這個大家一般都司空見慣了。所以沒什麼可講。內連線只是顯示滿足where後面的條件(st.student_id=sc.student_id)

B:左外連線sql

        select st.student_name,sc.object,sc.score,st.student_class
        from student st  left join score sc on st.student_id=sc.student_id
        執行結果:

左外連線是以左邊的表(student st  left)student為主表,score為從表。在查詢結果中全部展示主表的資訊。
也就出現上圖中Tom這個資訊不全。因為從表中沒有和Tom相匹配的資訊,因此才會出現Null值填充。

C:右外連線

      select st.student_name,sc.object,sc.score,st.student_class
      from student st right  join score sc on st.student_id=sc.student_id

      執行結果:

   

   右連線剛好和做連線想法。因此就會出現上圖的情況。

D:全外連線sql

    1. select st.student_name,sc.object,sc.score,st.student_class
     from student st  left join score sc on sc.student_id=st.student_id
    union
    select st.student_name,sc.object,sc.score,st.student_class
    from student st  RIGHT join score sc on sc.student_id=st.student_id

(本人使用mysql資料庫,因為mysql暫時還不支援全外連線full的功能,但是可以用多個left來實現)

  2.select st.student_name,sc.object,sc.score,st.student_class
     from student st  full  join score sc on sc.student_id=st.student_id(此語句針對一般資料庫)