I use Spring Boot with Hibernate. Currently I have 3 separate requests to a database:
- fetch all specific (with some WHERE conditions) data from table aaa
- fetch all specific (with some WHERE conditions) data from table bbb
- fetch max date of record that is found by WHERE clause with the same conditions from points 1 and 2.
Statement #1
SELECT count(a.id) as dateTo
from (
SELECT a.date_to
FROM aaa a
JOIN ramp r on a.ramp_id = r.id
JOIN warehouse w on r.warehouse_id = r.warehouse_id
WHERE w.id = 222
AND a.date_from >= '2022-08-20T00:00'
) allDates
Statement #2
SELECT count(b.id) as dateTo
from (
SELECT b.date_to
FROM bbb b
WHERE tw.warehouse.id = :warehouseId
AND tw.status = 'AVAILABLE'
) allDates
Statement #3
SELECT MAX(date_to) as dateTo
from (
SELECT a.date_to
FROM aaa a
JOIN ramp r on a.ramp_id = r.id
JOIN warehouse w on r.warehouse_id = r.warehouse_id
WHERE w.id = 222
AND a.date_from >= '2022-08-20T00:00'
UNION
SELECT b.valid_to as date_to
FROM bbb b
WHERE b.warehouse_id = 222
AND tw.status = 'AVAILABLE'
) allDates
Is it possible to do all this with one statement? I use MySql 5.7 so CTE is not available.
My code in Spring:
final long numberOfa = ...
final long numberOfB = ...
final LocalDate maxDate = ...
Expected result:
final MyObjectWithAllThreeValues myObject = repository.getAllDataWithOneQuery