Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

การ JOIN ตารางสองตารางใน MySQL ด้วย Foreign Key

ตัวอย่างการสร้างตาราง 2 ตารางและเชื่อมโยงด้วย Foreign Key แล้วทำ LEFT JOIN

สร้างตารางแรก (ParentTable)

mysql> create table ParentTable (
    -> UniqueId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
    -> EmployeeName varchar(10)
    -> );
Query OK, 0 rows affected (0.56 sec)

เพิ่มข้อมูล:

mysql> insert into ParentTable(EmployeeName) values('John');
mysql> insert into ParentTable(EmployeeName) values('Carol');
mysql> insert into ParentTable(EmployeeName) values('Sam');
mysql> insert into ParentTable(EmployeeName) values('Bob');

ข้อมูล ParentTable:

+----------+--------------+
| UniqueId | EmployeeName |
+----------+--------------+
|        1 | John         |
|        2 | Carol        |
|        3 | Sam          |
|        4 | Bob          |
+----------+--------------+

สร้างตารางที่สอง (ChildTable) พร้อม Foreign Key

mysql> create table ChildTable (
    -> UniqueId int NOT NULL PRIMARY KEY,
    -> EmployeeAddress varchar(100),
    -> CONSTRAINT fk_uniqueId FOREIGN KEY(UniqueId) references ParentTable(UniqueId)
    -> );
Query OK, 0 rows affected (0.54 sec)

เพิ่มข้อมูล:

mysql> insert into ChildTable values(1,'15 West Shady Lane Starkville, MS 39759');
mysql> insert into ChildTable values(2,'72 West Rock Creek St. Oxford, MS 38655');
mysql> insert into ChildTable(UniqueId) values(3);
mysql> insert into ChildTable values(4,'119 North Sierra St. Marysville, OH 43040');

ข้อมูล ChildTable:

+----------+-------------------------------------------+
| UniqueId | EmployeeAddress                           |
+----------+-------------------------------------------+
|        1 | 15 West Shady Lane Starkville, MS 39759   |
|        2 | 72 West Rock Creek St. Oxford, MS 38655   |
|        3 | NULL                                      |
|        4 | 119 North Sierra St. Marysville, OH 43040 |
+----------+-------------------------------------------+

คิวรี่ LEFT JOIN

mysql> select ParentTable.UniqueId, ParentTable.EmployeeName, ChildTable.EmployeeAddress
    -> from ParentTable left join ChildTable on ParentTable.UniqueId = ChildTable.UniqueId;

ผลลัพธ์:

+----------+--------------+-------------------------------------------+
| UniqueId | EmployeeName | EmployeeAddress                           |
+----------+--------------+-------------------------------------------+
|        1 | John         | 15 West Shady Lane Starkville, MS 39759   |
|        2 | Carol        | 72 West Rock Creek St. Oxford, MS 38655   |
|        3 | Sam          | NULL                                      |
|        4 | Bob          | 119 North Sierra St. Marysville, OH 43040 |
+----------+--------------+-------------------------------------------+