简体   繁体   English

如何将SQL查询的结果用作另一个查询中的字段

[英]How to use result of an SQL query as a field in another query

I have 2 tables 我有2张桌子

  • rentals 租金
  • entities 实体

Entities holds information about a thing that can be rented (rental care) Rentals holds the information for a specific rental of an entity, it is linked with a foreign key to the id of the entity: 实体保存有关可出租物品的信息(租赁服务)租金保存实体的特定租金信息,该信息与指向实体ID的外键链接:

Table: entities 表:实体

--------------------------
| id |      name         |
--------------------------
| 1  | Toyota Spacewagon |
| 2  | Volvo SuperCar    |

Table: rentals 表:租金

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

What I am trying to do is to get a list of ALL entities, along with their LAST rental date (to determine their current rental status), however I don't know how to phrase this in SQL. 我想做的是获取所有实体的列表,以及它们的最后租用日期(以确定它们当前的租用状态),但是我不知道如何在SQL中表达这一点。

My expected result: 我的预期结果:

-------------------------------------------------
| id |      name         |    rental_date       | 
-------------------------------------------------
| 1  | Toyota Spacewagon |  2016-06-30 12:00:00 |
| 2  | Volvo SuperCar    | (null)               |

Entities that have never been rented should return null for the rental date, cars that have been rented should have the last rental 从未租用的实体应在租车日期返回null,已租用的汽车应最后租车

Something akin to this, but with valid syntax... 类似于此,但语法有效...

SELECT id, name rental_date AS (SELECT rental_date FROM rentals WHERE entity_id = THIS_ROW'S_ENTITY) FROM entities;

Something like this should work: 这样的事情应该起作用:

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

This is a version without subquery: 这是一个没有子查询的版本:

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

You can do: 你可以做:

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;

Note: 注意:

I spent some time with this query and added the occurence of each entity in rentals table. 我花了一些时间进行此查询,并在Rentals表中添加了每个实体的出现。 Check it out :) 看看这个 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM