常规mysql表中的内部联接

时间:2015-11-10 11:39:01

标签: mysql inner-join

mysql我有一个名为users的表,其中包含系统中的用户列表......

id | name | surname | active
____________________________

1    John   Doe       True
2    Steve  Smith     True
...

然后还有另一张表cars,其中包含每个用户购买的汽车:

 id | model | brand | cc    | user_id
 ____________________________________

 1    330     BMW     2000    2
 2    Golf    VW      1600    1
 ...

我需要做的是编写一个执行以下操作的SQL语句:

for each of the users who have bought a car, 
show a list of them along with the number of cars they've purchased

例如: 用户Steve Smith共有1辆车。 用户John Doe共有1辆车。 (或任何数字)。

我想我必须做一些内部联接,但我不完全确定如何做到这一点。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

内部联接将提供。对于没有汽车的用户,他们不会出现。请注意,在id上使用列别名来区分具有两个表(id)中具有相同列名的连接的列。

请注意,Sally Higgins不会出现,因为inner join(a.k.a。join)会提取匹配项。除了其他人之外,还会使用left join来获取Sally,因为她缺少汽车细节。

模式

create table users
(   id int auto_increment primary key,
    firstName varchar(100) not null,
    lastName varchar(100) not null,
    active int not null
);
insert users(firstName,lastName,active) values ('John','Doe',1),('Steve','Smith',1),('Sally','Higgins',1);

create table cars
(   id int auto_increment primary key,
    model varchar(100) not null,
    brand varchar(100) not null,
    cc int not null,
    user_id int not null -- don't forget a foreign key constraint here
);
insert cars(model,brand,cc,user_id) values ('330','BMW',2000,2),('Golf','VW',1600,1),('Pinto','Ford',1000,1);

查询

select u.id,u.firstName,u.lastName,u.active,c.id as carId,c.model,c.brand,c.cc 
from users u 
join cars c 
on c.user_id=u.id;
+----+-----------+----------+--------+-------+-------+-------+------+
| id | firstName | lastName | active | carId | model | brand | cc   |
+----+-----------+----------+--------+-------+-------+-------+------+
|  1 | John      | Doe      |      1 |     2 | Golf  | VW    | 1600 |
|  1 | John      | Doe      |      1 |     3 | Pinto | Ford  | 1000 |
|  2 | Steve     | Smith    |      1 |     1 | 330   | BMW   | 2000 |
+----+-----------+----------+--------+-------+-------+-------+------+

离开加入Sally(无车莎莉)

select u.id,u.firstName,u.lastName,u.active,c.id as carId,c.model,c.brand,c.cc 
from users u 
left join cars c 
on c.user_id=u.id;
+----+-----------+----------+--------+-------+-------+-------+------+
| id | firstName | lastName | active | carId | model | brand | cc   |
+----+-----------+----------+--------+-------+-------+-------+------+
|  2 | Steve     | Smith    |      1 |     1 | 330   | BMW   | 2000 |
|  1 | John      | Doe      |      1 |     2 | Golf  | VW    | 1600 |
|  1 | John      | Doe      |      1 |     3 | Pinto | Ford  | 1000 |
|  3 | Sally     | Higgins  |      1 |  NULL | NULL  | NULL  | NULL |
+----+-----------+----------+--------+-------+-------+-------+------+