首页 > 解决方案 > 租同一辆车的人?

问题描述

我有一个关于 github 的项目,但我代表喜欢租一个汽车数据库以便更好地理解。我必须找到从 db 租同一辆车的人。我有一个 3 表:用户、租金和汽车。

User Table
+----+---------+
| id | name    |
+----+---------+
| 1  | alex    | 
| 2  | samuel  |
| 3  | michael |
+----+---------+
Rent Table
+--------+--------+
| rentId | userId |
+--------+--------+
| 68     | 1      |
| 77     | 3      |
| 93     | 2      |
| 99     | 3      |
| 105    | 1      |
+--------+--------+
Car Table
+---------+------+---------+
| model   | km   | rent    |
+---------+------+---------+
| kia     |  123 | 68      |
| bmw     | 389  | 93      |
| hyundai | 7979 | 99      |
| kia     | 3434 | 77      |
| kia     | 6565 | 105     |
+---------+------+---------+

我试过这个查询。(我使用rentId 来更好地理解关系)

SELECT id, name, rentId, model FROM user JOIN rent ON id = user_ID JOIN car ON rentID = rent ORDER BY model

它返回

+----+---------+---------+---------+
| id | name    | rent_ID | model   |
+----+---------+---------+---------+
| 1  | alex    | 68      | kia     |
| 2  | samuel  | 93      | bmw     |
| 3  | michael | 77      | kia     |
| 3  | michael | 99      | hyundai |
| 1  | alex    | 105     | kia     |
+----+---------+---------+---------+

但我想喜欢这个。它只显示租用同一辆车的人。如果同一个人再次雇用,也不要显示(不重复)。

+----+---------+---------+
| id | name    | model   |
+----+---------+---------+
| 1  | alex    | kia     |
| 3  | michael | kia     |
+----+---------+---------+

标签: mysql

解决方案


使用 CTE 计算出哪些模型对超过 1 人的雇佣人数超过 1 人,然后加入其他表以使用 distinct 来获取详细信息以进行重复数据删除

with cte as
(select c.model,count(distinct userid)
from car c
join rent r on r.rentid = c.rent
group by c.model having count(distinct userid) > 1
)
select distinct c.model,r.userid,u.name
from cte 
join car c on c.model = cte.model
join rent r on r.rentid = c.rent
join usr  u on u.id = r.userid;

推荐阅读