SQL多表查詢

SQL 提供了JOIN關鍵字來鏈接多張表的查詢(即鏈接的是SELECT結果集)基本分爲如下幾種:code

  • 內鏈接:JOIN / INNER JOIN,是最爲經常使用的一種鏈接,其效果是隻返回條件匹配的那條數據table

    • 等值鏈接:ON 子句中使用了運算符「=」,且鏈接的兩個字段最好是主鍵 例如select student.name, avg(sc.score) as avg_score from student join score on student.id = sc.id group by name;select

      name avg_score
      趙雷 89.66667
      錢電 70.00000
      孫風 80.00000
      李雲 33.33333
    • 不等鏈接:ON 子句中使用了不等於運算符,例如"<>" "<=>"等(能夠搜下 SQL 比較運算符)數據

    • 自鏈接:一張錶鏈接自身。例如select * from student a, student b where a.sex = b.sex and a.sex = '男';至關於作了次笛卡爾積運算,就不所有展現了查詢

    id name sex id name sex
    1 趙雷 1 趙雷
    2 錢電 1 趙雷
    3 孫風 1 趙雷
    4 李雲 1 趙雷
  • 外鏈接:除了返回條件匹配的數據,那些不知足的數據也會返回。根據鏈接表的順序可分爲:tab

    • 左(外)鏈接:LEFT JOIN / LEFT OUTER JOIN 以左表爲基錶鏈接右表,在右表中若沒有匹配到基表中的數據則返回 null 例如select stu.name, avg(sc.score) as avg_score from student stu left join sc on sc.id = stu.id group by stu.name;
    name avg_score
    趙雷 89.66667
    錢電 70.00000
    孫風 80.00000
    李雲 33.33333
    張三 null
    李四 null
    • 右(外)鏈接:RIGHT JOIN / RIGHT OUTER JOIN 以右表爲基錶鏈接左表,在左表中若沒有右匹配到基表中的數據則返回 null
  • 全(外)鏈接:FULL JOIN / FULL OUTER JOINco

    • 等同於 LEFT JOIN 結果集 UNION RIGHT JOIN 結果集
  • 交叉鏈接:CROSS JOIN (可用","代替)join

    • 等同於笛卡爾積 (因此不經常使用)
    • select * from table1 CROSS JOIN table2;<=> select * from table1, table2;
相關文章
相關標籤/搜索