2012-04-02 69 views
0

我想要做的是訪問表中正確的行,以便它返回正確的位置名稱,地址等。地址是正確返回,但有三個結果而不是一個。這些是我們的各個國際地點。適當的查詢或適當的規範化:MySQL

我的表格沒有正常標準化,或者我寫錯了我的查詢。我無法弄清楚哪一個。也許兩者都有一點。這裏是我的表格:

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 

我想加入他們在name_url。

因此,這裏是我的笨查詢/活動記錄(被翻譯成標準的MySQL很容易的):

$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(); 

但我回來從這三個結果。爲什麼,如果我使用name_url的where子句(正在正確傳遞給函數)?它是我有的加入類型嗎?我嘗試了左側和外側,並沒有幫助。

我在做什麼錯?

+1

在您擁有的示例數據中,所有3個經銷商都有相同的合作伙伴ID,它映射到所有3個位置。所以,不管你加入哪個地點,你都會得到所有3個經銷商= 3排。 – 2012-04-02 23:16:24

+0

我知道,但我也需要能夠對所有位置進行查詢?如果他們有唯一的ID,那麼如何獲得給定渠道合作伙伴的所有地點? – sehummel 2012-04-02 23:17:11

+0

你說你「想加入他們的name_url」,但你的查詢似乎並沒有這樣做。 ??? – 2012-04-03 00:21:27

回答

0

您的表格有一些問題。

大的紅旗是dealers有多行具有相同的id(這意味着channel_partner_id不能是主鍵)。

這是一個問題,因爲它看起來像dealers_locations應該是一個相交表。實現這種表的標準方法是獲取兩個表的主鍵,在這種情況下,這兩個表的主鍵是locationsdealers。由於dealer_locations沒有dealers的主鍵,因此不起作用。

以下是我反而會實現這個:

create table dealers (
    channel_partner_id int primary key, 
    name     varchar(30) 
); 

create table locations (
    location_id int primary key, 
    address  varchar(30), 
    name_url  varchar(30) 
); 

create table dealer_locations (
    location_id int, 
    foreign key (location_id) references locations(location_id), 
    channel_partner_id int, 
    foreign key (channel_partner_id) references dealers(channel_partner_id), 
    primary key (location_id, channel_partner_id) 
); 

注意事項dealer_locations由兩部分組成的主鍵。

+0

謝謝,馬特。這很棒。 – sehummel 2012-04-03 18:51:41