MySQL的JOIN(一):用法

上文的数据库栏目

两表连接,列名冲突

表结构如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
mysql> select * from Customers;
+----+-------+
| Id | Name |
+----+-------+
| 1 | Joe |
| 2 | Henry |
| 3 | Sam |
| 4 | Max |
+----+-------+
4 rows in set (0.00 sec)

mysql> select * from orders;
+----+------------+
| Id | CustomerId |
+----+------------+
| 1 | 3 |
| 2 | 1 |
+----+------------+
2 rows in set (0.00 sec)

不使用as改名:

1
2
3
4
5
6
7
8
mysql> select Name from Customers left join orders on Customers.Id = orders.CustomerId where CustomerId is null;
+-------+
| Name |
+-------+
| Henry |
| Max |
+-------+
2 rows in set (0.00 sec)

使用as改名:

1
2
3
4
5
6
7
8
mysql> select Name as Customers from Customers left join orders on Customers.Id = orders.CustomerId where CustomerId is null;
+-----------+
| Customers |
+-----------+
| Henry |
| Max |
+-----------+
2 rows in set (0.00 sec)