1. 程式人生 > 實用技巧 >MySQL資料庫之多表查詢inner join內連線

MySQL資料庫之多表查詢inner join內連線

內連線

  • 規則

    • 返回兩個表的公共記錄
  • 語法

    • inner join...on 語法
      • select * from 表1 inner join 表2 on 表1.公共欄位=表2.公共欄位
    • where 語法
      • select * from 表1,表2 where 表1.公共欄位=表2.公共欄位
MariaDB [sel]> select * from grades inner join resume on grades.name=resume.name;
+-------+---------+------+----+-------+-----------+
| name  | chinese | math | id | name  | skill     |
+-------+---------+------+----+-------+-----------+
| Sunny |      93 |   96 |  1 | Sunny | php       |
| Jerry |      97 |   91 |  3 | Jerry | php,mysql |
+-------+---------+------+----+-------+-----------+
# `2 rows in set (0.008 sec)`
MariaDB [sel]> select * from grades,resume where grades.name=resume.name;
+-------+---------+------+----+-------+-----------+
| name  | chinese | math | id | name  | skill     |
+-------+---------+------+----+-------+-----------+
| Sunny |      93 |   96 |  1 | Sunny | php       |
| Jerry |      97 |   91 |  3 | Jerry | php,mysql |
+-------+---------+------+----+-------+-----------+
# `2 rows in set (0.001 sec)`
-- 相同的欄位只顯示一次
mysql> select s.stuno,stuname,stusex,writtenexam,labexam from stuinfo s inner join stumarks m on s.stuno=m.stuno;
+--------+----------+--------+-------------+---------+
| stuno  | stuname  | stusex | writtenexam | labexam |
+--------+----------+--------+-------------+---------+
| s25303 | 李斯文    | 女     |          80 |      58 |
| s25302 | 李文才    | 男     |          50 |      90 |
| s25304 | 歐陽俊雄  | 男     |          65 |      50 |
| s25301 | 張秋麗    | 男     |          77 |      82 |
| s25318 | 爭青小子  | 男     |          56 |      48 |
+--------+----------+--------+-------------+---------+
# `5 rows in set (0.00 sec)`
  • 內連線中inner可以省略
    • select * from 表1 join 表2 on 表1.公共欄位=表2.公共欄位
MariaDB [sel]> select * from grades join resume on grades.name=resume.name;
+-------+---------+------+----+-------+-----------+
| name  | chinese | math | id | name  | skill     |
+-------+---------+------+----+-------+-----------+
| Sunny |      93 |   96 |  1 | Sunny | php       |
| Jerry |      97 |   91 |  3 | Jerry | php,mysql |
+-------+---------+------+----+-------+-----------+
# `2 rows in set (0.001 sec)`
  • 如何實現三表查詢
    • select * from 表1 inner join 表2 on 表1.公共欄位=表2.公共欄位 inner join 表3 on 表2.公共欄位=表3.公共欄位