# 笛卡儿积、左连接、右连接

### 啥是笛卡儿积

SELECT * FROM T1
+-------------+-------------+
| A           | B           |
+-------------+-------------+
| A1          | B1          |
| A2          | B2          |
+-------------+-------------+

SELECT * FROM T2
+-------------+-------------+
| B           | C           |
+-------------+-------------+
| B2          | C2          |
| B3          | C3          |
+-------------+-------------+


T1T2 做笛卡尔积

SELECT * FROM T1 CROSS JOIN T2
+-------------+-------------+-------------+-------------+
| A           | B           | B           | C           |
+-------------+-------------+-------------+-------------+
| A1          | B1          | B2          | C2          |
| A2          | B2          | B2          | C2          |
| A1          | B1          | B3          | C3          |
| A2          | B2          | B3          | C3          |
+-------------+-------------+-------------+-------------+


### 啥是连接

SELECT * FROM T1 JOIN T2 ON T1.B=T2.B
+-------------+-------------+-------------+-------------+
| A           | B           | B           | C           |
+-------------+-------------+-------------+-------------+
| A2          | B2          | B2          | C2          |
+-------------+-------------+-------------+-------------+


### 啥是左连接

LEFT JOIN - 列出左表中所有的元组，即使右表中没有可以与之相匹配的元组。话不多说，直接看结果就可以理解了。

SELECT * FROM T1 LEFT JOIN T2 ON T1.B=T2.B
+-------------+-------------+-------------+-------------+
| A           | B           | B           | C           |
+-------------+-------------+-------------+-------------+
| A2          | B2          | B2          | C2          |
| A1          | B1          | null        | null        |
+-------------+-------------+-------------+-------------+


### 啥是右连接

SELECT * FROM T1 RIGHT JOIN T2 ON T1.B=T2.B
+-------------+-------------+-------------+-------------+
| A           | B           | B           | C           |
+-------------+-------------+-------------+-------------+
| A2          | B2          | B2          | C2          |
|             |             | B3          | C3          |
+-------------+-------------+-------------+-------------+

posted @ 2019-03-13 20:49  Velscode  阅读(279)  评论(0编辑  收藏