mysql - 租同一辆车的人?
问题描述
我有一个关于 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 |
+----+---------+---------+
解决方案
使用 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;
推荐阅读
- angularjs - ui-router 状态更改后销毁 hls.js 流
- python - Python 问题,机械化机器人
- node.js - 无法使用节点连接 mongodb 和 socket.io
- google-apps-script - 使用 Google Apps 脚本简单邮件合并不会出现 0 值
- python - python中的pdfdump无法使用scapy
- java - javafx中同时有2个或更多线程
- javascript - 使用数据表的 HTML 图表
- docker - dokku 上的 .net core 2.0 网络应用程序在数字海洋上的每个 post 方法上返回 400
- apache-kafka - Kafka server.log 中的持续警告
- jquery - 如何通过 PartialView 的 AJAX 调用显示视图?