Actually, you can get project_ids in SQL. Assuming you need unique project identifiers for four projects with the latest log entries, SQL would look like this:
SELECT project_id, max(log.date) as max_date FROM logs GROUP BY project_id ORDER BY max_date DESC LIMIT 4;
Now you really need all the log information. In PostgreSQL 8.4 and later, you can use window functions, but this does not work in other versions / databases, so I will make it more complicated way:
SELECT logs.* FROM logs JOIN ( SELECT project_id, max(log.date) as max_date FROM logs GROUP BY project_id ORDER BY max_date DESC LIMIT 4 ) as latest ON logs.project_id = latest.project_id AND logs.date = latest.max_date;
Now, if you have access to the window processing functions, this is a little more neat (I think, anyway) and, of course, faster to execute:
SELECT * FROM ( SELECT logs.field1, logs.field2, logs.field3, logs.date rank() over ( partition by project_id order by "date" DESC ) as dateorder FROM logs ) as logsort WHERE dateorder = 1 ORDER BY logs.date DESC LIMIT 1;
Well, maybe itβs not so easy to understand, but honestly, it works faster on a large database.
I'm not quite sure how this translates to the syntax of an object, although even if it is. In addition, if you want to get other project data, you will need to join the project table.
Josh berkus
source share