Monday, April 13, 2009

How to do more than one table join in MySQL

I hope this saves people trying to learn this next level of MySQL a lot of time...

1. First, do your SELECT statement. You can select virtually any column and any number of columns from any table as long as you place the letter corresponding to the right table in front of the column's name (see Step 2).

SELECT a.animal, c.owner

2. Tell MySQL all the tables that will be involved in your join and substitute the names with letters to keep everything short.

FROM tableOne AS a, tableTwo AS b, tableThree AS c

3. Link all the tables you're dealing with together based on one and any common element between tables (I like to link one table to the next table in the same order I declared the tables in Step 2).

WHERE a.rowID = b.rowID
AND b.any_other_ID = c.any_other_ID


4. Get more picky with your search.

WHERE a.rowID = b.rowID
AND b.any_other_ID = c.anyotherID AND c.animal = "Cow"


or...

WHERE a.ghost LIKE "Scary" AND a.rowID = b.rowID
AND b.any_other_ID = c.any_other_ID AND c.animal = "Cow"


Etc....

Here's what the final query looks like...

SELECT a.animal, c.owner
FROM tableOne AS a, tableTwo AS b, tableThree AS c
WHERE a.ghost LIKE "Scary" AND a.rowID = b.rowID
AND b.any_other_ID = c.any_other_ID AND c.animal = "Cow"


Sample Result:

animal | owner : ghost (you won't see this column nor a.rowID, b.rowID etc.) :
Cow | mike : Scary :
Cow | jim : Scary :
Cow | bill : Scary :

Heck, lets join one more table while we're at it...

SELECT a.animal, c.owner, d.priceOfOwner
FROM tableOne AS a, tableTwo AS b, tableThree AS c, tableFour AS d
WHERE a.ghost = "Scary" AND a.rowID = b.rowID
AND b.any_other_ID = c.any_other_ID AND c.animal = "Cow"
AND c.rowID = d.rowID


Sample Result:

animal | owner | priceOfOwner : ghost :
Cow | mike | $1 : Scary :
Cow | jim | $2 : Scary :
Cow | bill | $5 : Scary :

Notice the importance of having a common column (rowID) in every table. Also, I usually open up as many browsers (running MySQL Admin) as the tables I want to join. I then load each table on each browser, minimize each browser, and place them side by side. I then write the most basic join statements (Steps 1-3) while going from one side of my computer screen to the other. I then make the query more picky from there (Step 4). Meanwhile, I test each query by using the MySQL Admin query box.

0 comments:

Post a Comment