snippetMajor
How to JOIN two table to get missing rows in the second table
Viewed 0 times
rowsthemissingjointwogetsecondhowtable
Problem
In a simple voting system as
for getting the list of elections a user has voted, the following JOIN is used
but how to get the list of elections a user has NOT voted?
CREATE TABLE elections (
election_id int(11) NOT NULL AUTO_INCREMENT,
title varchar(255),
CREATE TABLE votes (
election_id int(11),
user_id int(11),
FOREIGN KEYsfor getting the list of elections a user has voted, the following JOIN is used
SELECT * FROM elections
JOIN votes USING(election_id)
WHERE votes.user_id='x'but how to get the list of elections a user has NOT voted?
Solution
Use your existing query to get the opposite of the list you want. That list can then be checked against via NOT IN to get the desired list.
SELECT * FROM elections WHERE election_id NOT IN (
SELECT elections.election_id from elections
JOIN votes USING(election_id)
WHERE votes.user_id='x'
)Code Snippets
SELECT * FROM elections WHERE election_id NOT IN (
SELECT elections.election_id from elections
JOIN votes USING(election_id)
WHERE votes.user_id='x'
)Context
StackExchange Database Administrators Q#39344, answer score: 36
Revisions (0)
No revisions yet.