2016-09-20 6 views
0

私は3つのテーブルを持っています。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 FROM Components join Shops 

を使用して、これらの2つのテーブルを生じるはずである参加imageineテーブル、次は何私はそれを行うことを期待例えば

> 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 

に参加使用して

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 

そして最後に注文が参加し、私は前述のようにコマンド

> 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 

しかし、このコマンドを使用して生じるはずである使用

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

を例えば、それだけでランダムスロー私は何百行ものデータを取得しているので、crossjoinのように見えます。

ジョインについての理解は正しいですか?どこでミスを犯したのでなければ、どうすればこの仕事をすることができますか?手伝ってくれてありがとう!

答えて

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 

あなたが不足している主なものは、参加条件です。一般に、結合を実行するときは、2つの表の正しい行を照合するために使用されるconditonを指定する必要があります。たとえば、条件shops.componentId=components.idは、shopsの行とcomponentsの行が一致すると言います。ここで、componentIdは同じコンポーネントのidと同じです。

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

あなたは外部キー制約を宣言している場合は、この関係はないとしても、自動的に推測されていない:あなたが参加したいと思うとき

0

は、次の2つの表の行が一致するデータベースを伝える必要があります。

参加条件がないと、実際にはクロス参加を得ています。

関連する問題