What I am trying to do is to access the proper row in a table, so that it returns the right location name, address, etc. The address is returned correctly, but there are three results rather than one. These are our various international locations.
Either my tables aren’t normalized properly or I’m writing my query incorrectly. I can’t figure out which. Maybe a little of both. Here are my tables:
DEALERS TABLE:
channel_partner_id company
------------------ --------
626 Company Inc.
626 Company GmBH
626 Company Ltd.
DEALERS_LOCATIONS TABLE:
channel_partner_id location_id
------------------ -----------
626 18
626 19
626 20
LOCATIONS TABLE:
location_id address name_url
---------- -------------------- -------
18 1234 Anywhere St. anywhere-st
19 3245 Nowhere St. nowhere-st
20 90 Everywhere St. everywhere-st
I want to join them on the name_url.
So here’s my query in CodeIgniter/Active Record (which is translated into standard MySQL easy enough):
$this->db->where('l.name_url', $name_url);
$this->db->join('all_dealers_locations dl', 'dl.channel_partner_id = d.channel_partner_id', 'inner');
$this->db->join('all_locations l', 'l.location_id = dl.location_id', 'inner');
$row = $this->db->get('all_dealers d')->row();
But I get back three results from this. Why, if I am using the where clause of the name_url (which is being passed properly into the function)? Is it the type of join I have? I tried left and outer and that didn’t help.
What am I doing wrong?
Your tables have some issues.
The big red flag is that
dealershas multiple rows with the same id (which means thatchannel_partner_idcan not be the primary key).This is a problem because it looks like
dealers_locationsis supposed to be an intersection table. The standard way to implement such a table is to take the primary keys of the two tables, which in this case would belocationsanddealers. Sincedealer_locationsdoesn’t have the primary key ofdealers, it’s not going to work.Here’s how I would implement this instead:
Note the two-part primary key for
dealer_locations.