http://www.perlmonks.org?node_id=10721


in reply to Where should I use outer joins?

Given the following tables:
mysql> desc poll; +-------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+------------------+------+-----+---------+----------------+ | id | int(10) unsigned | | PRI | 0 | auto_increment | | poll | varchar(50) | | | | | +-------+------------------+------+-----+---------+----------------+
and
mysql> desc poll_votes; +---------+------------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------+------------------+------+-----+---------+----------------+ | id | int(10) unsigned | | PRI | 0 | auto_increment | | poll_id | int(10) unsigned | | | 0 | | | address | varchar(50) | | | | | +---------+------------------+------+-----+---------+----------------+
with data like:
mysql> select * from poll; +----+--------+ | id | poll | +----+--------+ | 1 | perl | | 2 | python | | 3 | C | | 4 | C++ | +----+--------+ mysql> select * from poll_votes; +----+---------+----------+ | id | poll_id | address | +----+---------+----------+ | 1 | 1 | junk | | 2 | 2 | junk | | 3 | 2 | morejunk | +----+---------+----------+
My first pass is this statement:
select p.poll from poll p left outer join poll_votes pv on pv.poll_id=p.id and pv.address='junk' where pv.poll_id is null;
It returns:
+------+ | poll | +------+ | C | | C++ | +------+

We do a left outer join (so we can see what we *didn't* get) on the address you want and have the 'where' clause give us what the join didn't find ('where pv.poll_id is null').
This should give you the polls for which this address has not voted.

Note: I assume you want to restrict votes to one vote per address per poll. You can easily accomplish this by removing id from poll_votes and making the primary key be both poll_id and address. This way, MySQL will enforce your policy for you.

Russ