笛卡爾積
select * from A join B
結果條數爲count(A)*count(B)
內連接
只有一個join關鍵字時,默認內連接
select * from A inner join B on A.id=B.id
和我們平常所寫的
select * from A,B where A.id=B.id
結果一樣,查詢交集(第一個是顯示,第二個是隱示)
結果記錄條數爲count(A、B共有)
左連接/左外連接
#outer可省
select A.id,B.id from A left outer join B on A.id = B.id
左邊的表(A)中的id值會全部展示,結果條數就是A表中所有的條數,B中沒有和A中的id值對應時,用NULL表示。
結果記錄條數count(A)
左表獨有
和左連接的區別就是,去除左連接結果中兩表的公共部分
select A.id,B.id from A left join B on A.id=B.id where B.id is null
結果記錄條數爲count(A)-count(A、B共有)
右連接/右外連接
#outer可省
select A.id,B.id from A right outer join B on A.id = B.id
和左連接差不多(反過來了),只是主表是右邊的表了(B),右邊的表全部保留
結果記錄條數爲count(B)
右表獨有
select A.id,B.id from A right join B on A.id=B.id where A.id is null
結果記錄條數count(B)-count(A、B共有)
全連接
oracle裏面有full [outer] join,但是在mysql中沒有full [outer] join。我們可以使用union來達到目的。union會自動去重,用 union all不會去重
select A.id,B.id from A left join B on A.id=B.id
union
slect A.id,B.id from A right join B on
A.id=B.id
結果條數爲count(A、B公共部分)+count(A獨有部分)+count(B獨有部分)。或count(A)+count(B)-count(A、B共有)