Jump to content

Most efficient way to select from several tables


Go to solution Solved by BenWeston,

Recommended Posts

Hi all

 

I have an InnoDB database with three tables – users, treatments and treatments_offered. The users table, predictably, stores user information with an ID for each. The treatments table stores a list of treatments with an ID for each and the treatments_offered table just stores the ID of a user and an ID of a treatment that they offer. Some users may only offer one treatment, some may offer 20+. Foreign keys are in place to make sure all this stays in sync.

 

My question is what is the quickest MySQL query I can run (via PHP but I'm not sure that actually matters), to select and list all the treatments provided by a user of ID, say, 3? Is there one query I can run or do I have to run several separate ones like this:

$treatment_ids = mysql_fetch_array(mysql_query("SELECT treatment_id FROM treatments_offered WHERE user_id = '$user_id';"), MYSQL_ASSOC);

$treatments = array();

foreach ($treatment_ids as $treatment_id) {
$temp = mysql_fetch_array(mysql_query("SELECT treatment FROM treatments WHERE id = '$treatment_id';"), MYSQL_ASSOC);
$treatments[] = $temp['treatment'];
}

That seems VERY inefficient to me – I think I'm missing something!

Edited by BenWeston

Great, thanks! So, perhaps, something like this (if I'm interpreting the JOIN documentation properly)?

SELECT treatment
FROM treatments 
JOIN treatments_offered ON (treatments_offered.treatment_id = treatments.id)
WHERE treatments_offered.user_id = '$user_id';

...as the users table will actually be redundant, seeing as the user's ID has a foreign key to user_id in treatments_offered?

Edited by BenWeston
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.