I am building a custom document versioning system in my website.
For this, I have 2 tables "vrm_document" and "vrm_document_active_document".
The first table contains all documents on my website, while the second table tells me which document is the active version for which user, so the second table contains the vrm_document_id field and a user_id field. Active documents are indicated by the parent_vrm_document_id being not NULL.
I have 2 kinds of documents:
- Default documents
- Documents uploaded by the users themselves
Each document that is uploaded contains versions, and min. 1 and max. 1 version has to be active at all times for the user. Thus the second table vrm_document_active_document will always contain the vrm_document_id combined with the user_id for the documents uploaded by the user himself.
However, the problem resides in the fact that default documents are documents that are provided by my website and will always be available to everyone. When a user does not have its own version of a default document, the default document will become the active version for that user by default. This is implicated. For active documents we do NOT insert rows in the vrm_document_active_document table. This means that if there are no versions of a default document active for the user, the default document becomes the active version by default for that user.
When displaying the documents with their versions to the user, I want to show all the versions in a list under each other, where the active version is displayed first, and then the others are sorted on the last modified time.
The following query gives me the correct results for documents that aren't default documents:
SELECT vd.*
FROM `vrm_document` AS `vd`
LEFT JOIN vrm_document_active_document AS vdad ON (vd.vrm_document_id = vdad.vrm_document_id AND vd.user_id = vdad.user_id)
WHERE ((`vd`.`parent_vrm_document_id` = 1 AND `vd`.`user_id` IN (2,18,21)) OR (`vd`.`vrm_document_id` = 1 ) )
ORDER BY vdad.vrm_document_id DESC, vd.timestamp_modified_utc DESC
However, as can be seen from the query, if we imagine that document ID 1 to be a default document, all fields in the vrm_document_active_document table will contain NULL, and thus it will sort based on the modified time.
The following is (in pseudo-code) what I need to achieve, is this possible using mariaDB SQL?
ORDER BY:
- if all values == NULL then value with default_document is first , then order by modified_utc
- else order by modified_utc
DB Fiddle: https://www.db-fiddle.com/f/71TUvdxFgFLhdncgo4BRre/1
EDIT: DB Fiddle added