Optimised query to select document and possible annotations
The best I've been able to come up with is to limit the size of the temporary table as much as possible by changing the inner WHERE to:

WHERE user_id=&lt;some_user_id_here&gt; AND document_id=&lt;some_document_id_here&gt;


It means the document ID has to be repeated in the statement, but at least means that the inner table is small, and pretty much guaranteed to be in-memory.