Click to See Complete Forum and Search --> : join 3 tables to a single table
rig99
12-06-2007, 03:51 AM
i am having problems joining my tables. i have 4 tables and 3 of them need to be joined to the same table.
the tables are a, b, c, and d and i need to join a, b, and c to d like this
a - d
b - d
c - d
i have tried something like this
---------------
select *
from a inner join d
on a.pid = d.batter inner join c
on c.pid = d.batter inner join b
on b.atbat = d.atbatid
----------------
but that doesn't work so i am kind of lost right now.
any help is greatly appreciated.
holiday
12-06-2007, 08:35 AM
http://www.tizag.com/sqlTutorial/sqljoin.php
a good table joining tutorial
rig99
12-06-2007, 10:56 AM
what i dont understand is how to join 3 tables to 1 because there is only 2 places to join to a single table in the syntax
d is the table i need to connect 3 other tables to but i dont know how to do it because i can only join 2 tables to 1 like this
from <a table>
join <table that needs to be connected to 3 tables> on .....
join <another table> on ....
how do i connect <a fourth table> to <table that needs to be connected to 3 tables>?
holiday
12-06-2007, 11:15 AM
ok, do all the tables has have an equal number of rows? This is a very important detail I need to know, let me explain. Is it like this:
OPTION #1
TABLE1 user_id, email, password
TABLE2 user_id, first_name, last_name, birth_date
TABLE3 user_id, web_site, aim
and for every user they would have one entry in each table and then you would join all the tables together by user id.
OPTION #2
TABLE1 user_id, email, password
TABLE2 user_id, videos
TABLE3 user_id, photos
in this option the user has videos and photos, however the user can have as many videos and photo as he wants. So the number of rows is not equal and the table 1 would have to be duplicated for every photo or video entry.
OPTION #3
TABLE1 user_id, email, password
TABLE2 user_id, first_name, last_name, birth_date
TABLE2 user_id, videos
TABLE3 user_id, photos
this is just a mix of Option 1 and 2
rig99
12-06-2007, 01:19 PM
actually i got it working by using this
----------
from d
join a on d.batter = a.pid
join c on d.pitcher = c.pid
join b on d.atbatid = b.atbatid
----------
im not sure why this works and my first one doesnt. i had a hard time finding how to join more than 2 tables and since i dont fully understand why this works i was wondering if anyone knew a site that focuses more on joins than just showing a 2 table join?
thanks for replying so quickly
holiday
12-06-2007, 01:24 PM
good luck... I had to go through days of trial and error before a had an ok understanding of it. Here is a link with some info on joining tables http://dev.mysql.com/doc/refman/5.0/en/join.html and just a tip: sometimes you need to use LEFT JOIN