2012-12-05 63 views
0

我有幾個表:模型,產品,規格,圖片和商店。
它們關聯如下:mysql如何加入這些表?

每個產品屬於(模型店)
每個圖片屬於(產品)
每個規格屬於(產品)

我需要的產品清單,

與商店,他們屬於(由product.store_id)
其中product.model_id = SOME_ID
只有在有規格的產品(由spec.product_id) 只有在產品照片(按picture.product_id)

我需要什麼類型的查詢?

感謝

+0

你至今嘗試過什麼? –

回答

1

你的定義是非常完整的,可以毫不誇張地翻譯:

select 
    -- Selecting all fields of product and store. 
    -- You can refine this by only listing the fields you need. 
    p.*, 
    s.* 
from 
    -- need a list of products, 
    product p 
    -- with the store they belongs to (by product.store_id) 
    inner join store s on s.store_id = p.store_id 
where 
    -- ONLY if there are specs for the product (by spec.product_id) 
    exists 
    (select 
     'x' 
    from 
     spec ps 
    where 
     ps.product_id = p.product_id) and 
    -- ONLY if a product has pictures (by picture.product_id) 
    exists 
    (select 
     'x' 
    from 
     pictures pp 
    where 
     pp.product_id = p.product_id) 
+0

如果您檢查我的查詢,它將返回OP所需的行 –

-1

試試這個::

Select * from 
from 
product p 
inner join model m on (p.model_id=m.id) 
inner join store s on (p.store_id=s.id) 
inner join picture pc on (p.picture_id=pc.id) 
inner join spec sp on (p.spec_id=sp_id) 

where product.model_id=some_id 
GROUP BY product.id 
+1

常見錯誤。連接所有表將導致查詢返回多行。例如,如果您有3張圖片和10個規格,則會爲每個產品返回30行。 – GolezTrol

+1

'選擇不同的p。*,s。*'可以解決這個問題...但它也可以使查詢更慢 – fthiella

+1

GROUP BY PRODUCTID也將解決問題 –