2016-09-20 79 views
0

我有三個表。在sqlite加入表

組件:

id | name | storage | bilance | 
    |  |   |   | 

商店

id | name | price | componentId | 
    |  |  |    | 

和訂單

id | item | amount | ... | 

部件的表保存產品。 商店表認爲,出售這種產品

因此,例如

component(1 , "wheel" , 15 , 15); 

出售輪店和商店

Shops(1 , "wheelShopone" , 150 , 1); 
Shops(2 , "Shoptwo" , 100 , 1) 

這basicly意味着你可以在更多的商店,例如1買輪: n關係

而且訂單包含要訂購的東西,例如

orders(1 , "wheel" , 5) 

我想要做的是找到在某些商店銷售的表單(如組件)中的所有元素。

我試圖使用連接如

> Select components.name as comp_name , components.id as comp_id , 
> shops.name as shop_name , shops.id as shop_id , orders.item as item , 
> orders.amount as order_amount from components join shops join orders 
> WHERE shop_name = some name 

什麼,我希望它做的是以下,使用

> Select components.name as comp_name , components.id as comp_id , 
> shops.name as shop_name , shops.id as shop_id FROM Components join Shops 

應導致imageine表

components          shops 
id | name | storage | bilance |  id | name | price | componentId| 
1 | wheel | 15  | 15  |  1 | One | 15 | 1   
2 | mouse | 1  | 1  |  2 | two | 5  | 1 
             3 | three| 5  | 2 

加入這兩個表

comp_name | comp_id | shop_name | shop_id 
wheel  | 1  | one  | 1 
wheel  | 1  | two  | 2 
mouse  | 2  | three  | 3 

最後用命令加入例如

id | item | amount | ... 
1 | wheel | 5  | ... 

使用如我前面所提到的命令

> Select components.name as comp_name , components.id as comp_id , 
> shops.name as shop_name , shops.id as shop_id , orders.item as order_item , order.amount as order_amount FROM Components join Shops 
> join Orders on components.name = orders.item 

應導致

comp_name | comp_id | shop_name | shop_id | item | amount 
wheel  | 1  | one  | 1  | wheel| 5 
wheel  | 1  | two  | 2  | wheel| 5 

但是使用這個命令,它只是拋出隨機表中加入了看起來像交叉連接的表,因爲我得到了數百行數據。

我對加入的理解是否正確?如果沒有我犯錯的地方,我怎麼能做這個工作?感謝幫助!

回答

0

同比可能希望這樣的事情:

SELECT components.name as comp_name, 
     components.id as comp_id, 
     shops.name as shop_name, 
     shops.id as shop_id, 
     orders.item as item, 
     orders.amount as order_amount 
FROM shops JOIN components ON shops.componentId=components.id 
      JOIN orders ON components.id=orders.item 
WHERE shop_name = some name 

主要的事情你缺少的連接條件。一般來說,在進行連接時,必須指定一個條件,用於匹配兩個表中的正確行。例如,條件shops.componentId=components.id表示來自shops的匹配行與來自components的行相同,其中componentId與組件id相同。

0

當你想要做一個連接,你必須告訴其兩個表中的行與數據庫:

SELECT ... 
FROM Components 
JOIN Shops ON Components.id = Shops.componentId; 

當你聲明外鍵約束,這種關係不會自動推導,甚至沒有。

沒有連接條件,你確實得到了一個交叉連接。