gpt4 book ai didi

mysql - 常规 mysql 表中的内连接

转载 作者:行者123 更新时间:2023-11-29 11:53:23 29 4
gpt4 key购买 nike

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 辆车。 (或任何数字)。

我认为我必须进行某种内部联接,但我不完全确定如何做到这一点。

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

最佳答案

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

请注意,Sally Higgins 不会出现,因为 inner join(又名 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 |
+----+-----------+----------+--------+-------+-------+-------+------+

关于mysql - 常规 mysql 表中的内连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33629116/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com