1. 程式人生 > 其它 >mysql 連線查詢

mysql 連線查詢

連線語法

select 欄位
from 表名1,表名2
where 表名1.key =  表名2.key
[group by 欄位]
[having 條件]
[order by 欄位 [desc|asc]]
select 欄位...
from 表名1
【連線型別】join 表名2 on 表名1.key = 表名2.key
[where 條件]
[group by 條件]
[having 條件]
[order by 欄位 [desc|asc]

等值連線

查詢學生id,名字,班級名稱 方法一:

SELECT
    student.id,
    student.name student_name,
    class.name class_name 
FROM
    student,
    class 
WHERE
    student.class_id = class.id;
+----+--------------+------------+
| id | student_name | class_name |
+----+--------------+------------+
|  1 | 張三         | 班級1      |
|  2 | 王五         | 班級1      |
|  3 | 李四         | 班級1      |
|  4 | 小紅         | 班級2      |
|  5 | 小花         | 班級2      |
|  6 | huyongjian   | 班級3      |
|  7 | Join         | 班級3      |
+----+--------------+------------+

方法二:

SELECT
    student.id,
    student.name student_name,
    class.name class_name 
FROM
    student
    INNER JOIN class ON student.class_id = class.id;
+----+--------------+------------+
| id | student_name | class_name |
+----+--------------+------------+
|  1 | 張三         | 班級1      |
|  2 | 王五         | 班級1      |
|  3 | 李四         | 班級1      |
|  4 | 小紅         | 班級2      |
|  5 | 小花         | 班級2      |
|  6 | huyongjian   | 班級3      |
|  7 | Join         | 班級3      |
+----+--------------+------------+

左連線

SELECT
    student.`id`,
    student.`name` student_name,
    class.`name` class_name 
FROM
    student
    LEFT JOIN class ON student.`class_id` = class.`id`;
+----+--------------+------------+
| id | student_name | class_name |
+----+--------------+------------+
|  1 | 張三         | 班級1      |
|  2 | 王五         | 班級1      |
|  3 | 李四         | 班級1      |
|  4 | 小紅         | 班級2      |
|  5 | 小花         | 班級2      |
|  6 | huyongjian   | 班級3      |
|  7 | Join         | NULL       |
+----+--------------+------------+
7 rows in set (0.00 sec)

右連線

SELECT
    student.`id`,
    student.`name` student_name,
    class.`name` class_name 
FROM
    student
    RIGHT JOIN class ON student.`class_id` = class.`id`;
+------+--------------+------------+
| id   | student_name | class_name |
+------+--------------+------------+
|    3 | 李四         | 班級1      |
|    2 | 王五         | 班級1      |
|    1 | 張三         | 班級1      |
|    7 | Join         | 班級2      |
|    6 | huyongjian   | 班級2      |
|    5 | 小花         | 班級2      |
|    4 | 小紅         | 班級2      |
| NULL | NULL         | 班級3      |
+------+--------------+------------+
8 rows in set (0.00 sec)