I have a question about a particular query I’d like to execute against a PostgreSQL table. Although I welcome criticism of the table scheme I’ve used I’m going to be more appreciative of answers to my actual question!
I’m using the uuid-ossp postgresql-contrib module and have the following table structure:
Column | Type | Modifiers | Storage | Description
---------------------+-----------------------------+-----------+----------+-------------
revision_id | uuid | not null | plain |
document_id | uuid | not null | plain |
user_id | uuid | not null | plain |
datetime_edited | timestamp without time zone | not null | plain |
contents | text | not null | extended |
Indexes:
"document_pkey" PRIMARY KEY, btree (revision_id)
The idea is that:
- A document may have one or more revisions. Revisions are not deleted. In order to update a document a new row is inserted with a new
revision_idbut an identicaldocument_id. revision_idis unique across all revisions for all documents.contentsis a blob of data that represents the document, anduser_ididentifies who updated the document.
I’m struggling to come up with a query that returns all the latest revisions for all documents created by a particular user. I know I can do, for example:
select * from document where user_id = '6a2aabc417b34ef99b14b10eaa8e9313';
but this returns all the documents. How do I drill down and ask for a grouping by document_id, and also LIMIT 1 and return the newest revision_id based on datetime_edited?
EDIT: Since a document can have one or more revisions I’ve been far to vague in saying “all documents created by a user”. By created I mean that the user has contributed one or more revisions to the documents, i.e. there is at least one revision where the user edited the document.
Is something like this even achievable in one query, or do I need to hit the database several times to achieve this?
EDIT: revision_id is not monotonically increasing. It’s a random UUID. Hence, max(revision_id) != max(datetime_edited).
An alternate form: