简体   繁体   中英

SQLite / Java Compare most recent time stamp with one from 24hr ago for each name

I am trying to get data from the most recent time stamp, and the time stamp from 24 hr ago for each name in the table. My current method makes two seperate queries and combines the results. This, however is quite slow, and also prevents me from sorting the data (by comments etc)

The below query gets the data from 24 hr ago (last)

SELECT Price, comment ,name, timestamp
FROM details INNER JOIN car ON details .ID=car.ID
WHERE timestamp >= datetime('now','-1 day') and name = 'BMW'
order by timestamp asc limit 1

I then have another similar query which returns data with the most recent time stamp (first).

I have a method in Java which contains the above queries, and passes in a new car name into the name = " " part. This returns first and last for each car, I then compare price and comment details and return the results.

However this is proving to be very slow process. And it also means that I cant order the results efficiently.

I have also tried with union, however it does provide the desired results

SELECT Price, comment ,name, max(timestamp)
FROM details INNER JOIN name ON details .ID=name .ID

UNION
SELECT Price, comment,name, min(timestamp)
FROM details  INNER JOIN name ON details .ID=name .ID
WHERE timestamp >= datetime('now','-1 day')
group by name
order by comment desc
limit 40

What is the correct way to perform this query?

Assuming that cars.name is unique (ie equivalent to cars.id and that you want the results on separate rows, you can do the aggregation in a subquery to get the two timestamps. Then, join in the additional information you want:

SELECT c.name, d.Price, d.comment, d.name, d.timestamp
FROM car c JOIN
     details d 
     ON d.ID = c.ID JOIN
     (SELECT dd.ID, MAX(dd.timestamp) as maxts, MIN(dd.timestamp) as mints
      FROM detail dd
      WHERE dd.timestamp >= datetime('now', '-1 day')
      GROUP BY dd.ID
     ) dd
     ON dd.ID = c.ID AND d.timestamp IN (dd.mints, dd.maxts)
ORDER BY timestamp asc;

To get one output row for each name, use GROUP BY:

SELECT Price, comment, name, max(timestamp)
FROM details INNER JOIN name USING (ID)
GROUP BY name.ID

UNION ALL

SELECT Price, comment, name, min(timestamp)
FROM details INNER JOIN name USING (ID)
WHERE timestamp >= datetime('now','-1 day')
GROUP BY name.ID

ORDER BY ...;

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