petrjanda Veteran


Joined: 05 Sep 2003 Posts: 1557 Location: Brno, Czech Republic
|
Posted: Fri May 04, 2012 3:27 am Post subject: Tricky SQL query (any sql experts here?) |
|
|
Ok here is the data you KNOW - Aircraft ID, and a Timestamp before you run the query.
You have a table that tracks every change done to a Part (instead of UPDATE, it does INSERT INTO on every update to hold a complete history of the PartID)
| Code: |
RevisionID, PartID, AircraftID, RecordCreatedAt
1, 5, 5, 2012-04-01 12:00:00 - partID 5 created on aircraft 5
2, 5, 3, 2012-05-01 12:00:00 - partID 5 moved to aircraft 3
3, 5, 3, 2012-05-01 12:30:00 - partID 5 update - see the time change
4, 5, 4, 2012-05-03 12:00:00 - partID 5 moved to aircraft 4
5, 6, 3, 2012-05-01 12:00:00 - partID 6 created on aircraft 3
|
RevisionID is autoincrement.
And this is the goal:
Get all the parts present on an AircraftID 3 at the given time 2012-05-02 12:00:00. I know I can do this in the code, but for the sake of performance I want to do this at the SQL level.
Using the data above, the final SELECT should return:
| Code: |
RevisionID, PartID, AircraftID, RecordCreatedAt
3, 5, 3, 2012-05-01 12:30:00 - notice the returned row shows the most up-to-date version, the previous version made at 12:00:00 is ignored
5, 6, 3, 2012-05-01 12:00:00
|
As those 2 parts where present on aircraftID 3 at the given time.
The database is sqlite3.
Do we have any SQL experts that can help me out on this? _________________ There is, a not-born, a not-become, a not-made, a not-compounded. If that unborn, not-become, not-made, not-compounded were not, there would be no escape from this here that is born, become, made and compounded. - Gautama Siddharta |
|
GoldenMouse Tux's lil' helper


Joined: 29 Sep 2005 Posts: 112
|
Posted: Sat May 05, 2012 6:23 am Post subject: |
|
|
It's too late to come up with a query for you; I tried, but my brain is too fried to pull it together. I'll try to come back and answer this better, but it seems as if you need a subquery or two in there.
Start with a query that returns the most recent record before your stated time for a given part and a given aircraft:
SELECT *
FROM `TheTable`
WHERE `PartID` = ?
AND `AircraftID` = ?
AND `RecordCreatedAt` < ?
ORDER BY `RecordCreatedAt` DESC
LIMIT 1
You then need to wrap this such that it runs once for each PartID on that aircraft. I know it can be done, but it's past 2am right now.  |
|