我有2张桌子
实体持有有关可租用物品的信息(租赁护理) Rentals保存实体特定租赁的信息,它与实体ID的外键相关联:
--------------------------
| id | name |
--------------------------
| 1 | Toyota Spacewagon |
| 2 | Volvo SuperCar |
---------------------------------------------------------------
| id | entity_id | rental_date | return_date |
---------------------------------------------------------------
| 1 | 1 | 2016-06-30 12:00:00 | 2016-07-01 12:00:00 |
| 2 | 1 | 2016-06-28 12:00:00 | 2016-07-30 10:00:00 |
| 3 | 1 | 2016-05-30 09:00:00 | 2016-06-01 13:00:00 |
我想要做的是获取所有实体的列表,以及他们的最后租赁日期(以确定他们当前的租赁状态),但我不知道如何在SQL中对此进行短语。
-------------------------------------------------
| id | name | rental_date |
-------------------------------------------------
| 1 | Toyota Spacewagon | 2016-06-30 12:00:00 |
| 2 | Volvo SuperCar | (null) |
从未租用过的实体应该在租赁日期返回null,已经租用的汽车应该有最后一次出租
类似于此的东西,但语法有效...
SELECT id, name rental_date AS (SELECT rental_date FROM rentals WHERE entity_id = THIS_ROW'S_ENTITY) FROM entities;
答案 0 :(得分:1)
这样的事情应该有效:
SELECT e.Id,e.name,r.rental_date
FROM entities e
LEFT JOIN
(
SELECT entity_id,MAX(rental_date) AS rental_date
FROM rentals
GROUP BY entity_id
) r ON r.entity_id=e.Id
答案 1 :(得分:1)
这是一个没有子查询的版本:
SELECT a.id, a.name, MAX(b.rental_date)
FROM entities a
LEFT JOIN rentals b on a.id = b.entity_id
GROUP BY a.id, a.name
答案 2 :(得分:0)
你可以这样做:
Select r.rentedtimes,r.lastrentaled , e.id , e.`name`
from entities e
left join (
Select count(entity_id) as rentedtimes,id,entity_id,max(return_date) as lastrentaled
from rentals
group by entity_id)r
on e.id = r.entity_id
group by e.id;
注意:
我在这个查询上花了一些时间,并在租赁表中添加了每个实体的出现。看看:)