Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery
 
PerlMonks  

Answer: Where should I use outer joins?

by Russ (Deacon)
on May 09, 2000 at 11:35 UTC ( #10721=categorized answer: print w/replies, xml ) Need Help??

Q&A > database programming > Where should I use outer joins? - Answer contributed by Russ

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

Log In?
Username:
Password:

What's my password?
Create A New User
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (3)
As of 2016-12-11 11:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    On a regular basis, I'm most likely to spy upon:













    Results (169 votes). Check out past polls.