So, let’s say I have a users table and a pages table. Let’s say that I want to allow users to hide/forget/ignore certain pages. At this point, I can think of two possible approaches:
An outer join with null matching:
I can create a separate ignored_pages table with columns user_id and page_id, writing to it INSERT INTO ignored_pages (user_id, page_id) VALUES (1,2); when the user with ID of 1 ignores a page with ID of 2.
Then I can run something like SELECT pages.* FROM pages LEFT OUTER JOIN ignored_pages ON pages.id = ignored_pages.page_id WHERE ignored_pages.user_id = 1 AND ignored_pages.id IS NULL;
EDIT: Joe Stefanelli pointed on an error in my query. It should be SELECT pages.* FROM pages LEFT OUTER JOIN ignored_pages ON pages.id = ignored_pages.page_id AND ignored_pages.user_id = 1 WHERE ignored_pages.id IS NULL;
A subquery and NOT IN:
I can use the same many-to-many table and then run something like SELECT pages.* FROM pages WHERE page_id NOT IN (SELECT page_id FROM ignored_pages WHERE user_id = 1);.
Is there a best practice or series of rules of thumb or (likely) a better approach to this problem than the one I’m taking?
Your best performance may actually be a
NOT EXISTSIf you decide to stick with your
LEFT JOINoption, you’ll need to correct that query to testuser_idon the join condition rather than theWHEREclause.