I have a PostgreSQL table containing users, a PostgreSQL table containing documents, and a table mapping the users to the documents they’ve read. Like so:
Table: users
------------
| oid |
| username |
| ... |
------------
Table: documents
------------
| oid |
| title |
| ... |
------------
Table: users_documents
-----------------
| oid |
| user_oid |
| document_oid |
-----------------
Whenever a user reads a document, a record is added to users_documents with their user id and the document id. This is all working fine.
What I want to do though is select a random unread document for a given user. I feel like I should be able to do this with a fairly simple JOIN, but I can’t get my head around exactly what the query should look like.
Can someone help please? Thanks.
For most data, you can go to the users_documents table. For instance,
a query of the documents read by user_oid = ? would be
However, you want the records which are missing.
You can do an outer join, and find the NULLs in the results.
It is important that the “users_documents.user_oid = ?” be in the join in the FROM clause rather than in a WHERE clause, because it would not work in the WHERE clause.