數據庫幾個連接的測試

晚上看了一個同事在寫sql,覺得自己有段時間沒寫sql了,突然好想寫寫,然後就在Oracled

的PL/SQL Developer 寫了幾個簡單的語句來玩下,並且寫寫運行的結果。

試驗準備:
[list]
[*]
[*]teacher,student,tea_stu 三個表 表的字段如下:
[*]teacer : teaid , name , age
[*]student: stuid , name , age
[*]tea_stu: teaid , stuid
[/list]

假設tea_stu 這個表現在有13條記錄 teacher 有4條記錄 student 有4條記錄

select teaid from tea_stu union all select teaid from teacher

共17條記錄 = 兩個表記錄的相加的總和 即沒有去掉重複

select teaid from tea_stu union select teaid from teacher

共4條記錄 = 兩個表記錄的相加的總和 並去掉重複

select * from tea_stu , teacher

共52條記錄 就是笛卡爾積 相當於

select * from tea_stu , teacher on 1=1 (inner join 一定要加 on + 條件。)

select * from tea_stu left join teacher on tea_stu.teaid = teacher.teaid 共13條記錄

因爲tea_stu是主表,有13條記錄 teacher表是從表,如果主表中有和從表相對應的記錄 整

條記錄都不會爲空。如果沒有相對應的記錄的話,右邊就是顯示爲空。

補充:inner join 和 left join 都一定要加 on a.id = b.id這樣的條件。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章