简体   繁体   中英

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

I have 2 tables

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

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.

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

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. Check it out :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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