本文参考并引用图片源自Visual Representation of SQL Joins
目录
Data
- 登录并下载sql文件Visual Representation of SQL Joins
ls -lh Visual_SQL_JOINS.zip
-rw-r--r--@ 1 yuanlin staff 1.1K 8 29 22:13 Visual_SQL_JOINS.zip
unzip Visual_SQL_JOINS.zip
sed -i "" 's/\[//g' SQL_Tables.sql
sed -i "" 's/\]//g' SQL_Tables.sql
sed -i "" 's/GO/;/g' SQL_Tables.sql
mycli -uroot -p123456
CREATE DATABASE demo;
USE demo;
SOURCE ./SQL_Tables.sql;
SHOW tables;
+----------------+
| Tables_in_demo |
+----------------+
| Table_A |
| Table_B |
+----------------+
SELECT * FROM Table_A;
+----+------------+
| PK | Value |
+----+------------+
| 1 | FOX |
| 2 | COP |
| 3 | TAXI |
| 4 | LINCOLN |
| 5 | ARIZONA |
| 6 | WASHINGTON |
| 7 | DELL |
| 10 | LUCENT |
+----+------------+
SELECT * FROM Table_B;
+----+-----------+
| PK | Value |
+----+-----------+
| 1 | TROT |
| 2 | CAR |
| 3 | CAB |
| 6 | MONUMENT |
| 7 | PC |
| 8 | MICROSOFT |
| 9 | APPLE |
| 11 | SCOTCH |
+----+-----------+
Inner Join
SELECT A.PK AS A_PK, A.Value AS A_Value, B.PK AS B_PK, B.Value AS B_Value
FROM Table_A A
INNER JOIN Table_B B
ON A.PK = B.PK;
+------+------------+------+----------+
| A_PK | A_Value | B_PK | B_Value |
+------+------------+------+----------+
| 1 | FOX | 1 | TROT |
| 2 | COP | 2 | CAR |
| 3 | TAXI | 3 | CAB |
| 6 | WASHINGTON | 6 | MONUMENT |
| 7 | DELL | 7 | PC |
+------+------------+------+----------+
inner_join.png
Left Join
SELECT A.PK AS A_PK, A.Value AS A_Value, B.PK AS B_PK,
B.Value AS B_Value
FROM Table_A A
LEFT JOIN Table_B B
ON A.PK = B.PK;
+------+------------+--------+----------+
| A_PK | A_Value | B_PK | B_Value |
+------+------------+--------+----------+
| 1 | FOX | 1 | TROT |
| 2 | COP | 2 | CAR |
| 3 | TAXI | 3 | CAB |
| 6 | WASHINGTON | 6 | MONUMENT |
| 7 | DELL | 7 | PC |
| 4 | LINCOLN | <null> | <null> |
| 5 | ARIZONA | <null> | <null> |
| 10 | LUCENT | <null> | <null> |
+------+------------+--------+----------+
left_join.png
Right Join
SELECT A.PK AS A_PK, A.Value AS A_Value, B.PK AS B_PK,
B.Value AS B_Value
FROM Table_A A
RIGHT JOIN Table_B B
ON A.PK = B.PK;
+--------+------------+------+-----------+
| A_PK | A_Value | B_PK | B_Value |
+--------+------------+------+-----------+
| 1 | FOX | 1 | TROT |
| 2 | COP | 2 | CAR |
| 3 | TAXI | 3 | CAB |
| 6 | WASHINGTON | 6 | MONUMENT |
| 7 | DELL | 7 | PC |
| <null> | <null> | 8 | MICROSOFT |
| <null> | <null> | 9 | APPLE |
| <null> | <null> | 11 | SCOTCH |
+--------+------------+------+-----------+
right_join.png
Full Join
SELECT A.PK AS A_PK, A.Value AS A_Value, B.PK AS B_PK, B.Value AS B_Value
FROM Table_A A
FULL OUTER JOIN Table_B B
ON A.PK = B.PK;
full_join.png
网友评论