mysql joins and data mapping

Thursday 28th June 2007 11:40 PM

TAGS: mySQL, join
When you start dealing with large sets of data, you really need to think about your database design and how it will scale in size and for different purposes in the future. Joins can help you keep things organised and flexible when you're dealing with "sets" of data.

Suppose you have a table containing a list of foods, and a table containing a list of people...



Now we want to keep track of which users like which type of foods. They are given a choice to pick which ones they prefer, and we're going to use some "mapping" to associate them with the foods.

Here's another table, called foodMap, which has the ID of the food chosen, and the ID of the user who chose it.


To get a list of the user "Stans" favourite foods, can use a fairly simple JOIN query such as...

SELECT foods.name
FROM foodMap
LEFT JOIN foods ON foodMap.foodID=foods.id
WHERE foodMap.userID=1



Basically, we're selecting all the rows stored in the "foodMap" table, and attaching to the left of that, the food name. The join pivots on the foodID in the foodMap table being equal to the foods tables id field. If there is no match, then that will not be selected.

Comments on this article:


#1 Josh says:

Friday 29th June 2007 11:24 AM

Dont know if you were going to touch base on this in another article, but just thought I'd point out that you should definetely add indexes on your relational table and for the corresponding fields in the related tables as joins can increase cpu load, especially when querying large amounts of data.

And yes that was a very long sentence.

#2 Gavin says:

Friday 29th June 2007 05:00 PM

You are a wise man Josh. ;)

Totally correct with the importance of indexing, I'll plan to cover a bit of that later on. It can be a bit of a juggling act sometimes working out if a JOIN'd query is quicker than several simple SELECT's


Add Comment:


Make a Comment

*Nb, all comments are moderated to prevent spam or inappropriate content.








netforge logo
netforge provides high quality and friendly website design services to business. We're Australian based and reliable... (find out more).