Say I have four tables, users, contacts, files, and userfiles.
Users can upload files and have contacts. They can choose to share their uploaded files with their contacts.
When a user selects one or more of their uploaded files, I want to show a list of their contacts that they are not already sharing all of their selected files with. So if they selected one file, it’d show the contacts that can’t already see that file. If the selected multiple files, it’d show the contacts that can’t already see all of the files.
Right now I’m trying a query like this (using sqlite3):
select users.user_id, users.display_name
from users, contacts, userfiles
where contacts.user_id = :user_id
and contacts.contact_id = users.user_id
and (
userfiles.user_id != users.user_id
and userfiles.file_id != :file_id
);
Note that the last line is auto-generated in a loop in the case of multiple selected files.
Where :user_id is the user trying to share the file, and :file_id is the file which, if a user can already see that file, they are omitted from the result. What I end up with is a list of contacts which are sharing any files other than the selected one, so if the user is sharing multiple files with any one contact, that contact shows up in the list multiple times.
How can I avoid the duplicates? I just want to check if the file is already being shared, not grab all of the contents of userfiles that don’t involve a particular file or files.
select users.user_id, users.display_name
from users, contacts as c
where c.user_id = :user_id
and c.contact_id = users.user_id
and not exists (
select user_id
from userfiles as uf
where uf.user_id = c.contact_id
and uf.file_id in (:file_ids)
);
Note that
:file_idsis all your file_id’s, seperated with commas. No more looping to run multiple queries!EDIT:
This is the data I’m running as a test:
Then, if I run my query with
:user_id= 5 and:files_id= 20,30, I get:That seems like what you want, as I understand it, that is, the only users who do not have all the file ID’s. If I misunderstood something, please let me know.