常规 mysql 表中的内部联接

Inner join in regular mysql tables

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

id | name | surname | active
____________________________

1    John   Doe       True
2    Steve  Smith     True
...

然后还有另一个 table 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 辆汽车。 (或任何数字)。

我想我必须进行某种内部联接,但我不完全确定该怎么做。

如有任何帮助,我们将不胜感激。

内部联接将实现这一点。对于没有汽车的用户,他们不会出现。请注意在 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 |
+----+-----------+----------+--------+-------+-------+-------+------+

左加入接莎莉(无车莎莉)

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 |
+----+-----------+----------+--------+-------+-------+-------+------+