2012-01-21 48 views
0

現在我有4個表:EAV查詢和表

table categories: 
-id 
-category 

table products: 
-id 
-product 
-price 
-image 

table attributes: 
-id 
-attribute 
-product_id 

table values: 
-product_id 
-attribute_id 
-value 

我正與查詢:

SELECT `id`, `product`, `price`, `image` FROM `products` WHERE `category_id` = $category->id 

現在,我得到的產品陣列此類別和需要得到它的屬性: 一個查詢:

SELECT `products`.`id` AS `product_id`, 
`attributes`.`attribute`, 
`values`.`value` 
FROM `products` LEFT JOIN `attributes` ON (`attributes`.`product_id` = `products`.`id`) 
LEFT JOIN `values` ON (`values`.`product_id` = `products`.`id` 
AND `values`.`attribute_id` = `attributes`.`id`) 
WHERE `products`.`id` IN ($ids) 

而且它得到與值的屬性,但我想知道一兩件事: 如果有可能擺脫table attributes中的'product_id'列並獲取沒有該列的屬性和值?現在,例如一大堆複製的屬性:

table attributes 
-id 1 
-attribute Weight 
-product_id 1 

-id 2 
-attribute Weight 
-product_id 2 

雖然我只想:

-id 1 
-attribute Weight 

對不起我的英語水平,如果我的帖子的一些部分需要更多的解釋,請讓我現在

+0

您缺少'product'表的描述中的'category_id'。 –

+0

拋開EAV的侷限性,你的設計表明不同的產品可以有不同的允許屬性(存儲在'屬性'表中的屬性)。如果你不想要這樣的功能,你可以使用@ vucetica的方法。 –

回答

0

這取決於你是否希望你的屬性是產品特定的,但你明顯不這樣做。另外,如果您的屬性表中包含您的值表,則不需要product_id。所以,你的表更有意義,如果他們是這樣的:

table categories: 
-id 
-category 

table products: 
-id 
-product 
-price 
-image 
-category_id 

table attributes: 
-id 
-attribute 
-product_id 

table values: 
-attribute_id 
-value 

其實,我想使它成爲了很多更簡單的EAV:

table categories: 
-id 
-category 

table products: 
-id 
-product 
-price 
-image 
-category_id 

table attributes: 
-id 
-product_id 
-attribute 
-value 

然後,您的查詢看起來像:

SELECT id, product, price, image, attribute, value 
FROM products 
    INNER JOIN attributes ON products.id = attributes.product_id 
WHERE products.category_id = :category_id 

確保您有適當的索引。此外,您希望通過選擇產品ID並將其放入IN來執行此操作是一種不好的做法。

+0

但是,如果我有10個屬性? – nazarov

+0

它將返回10行。你不想那樣嗎? –

+0

這會將OP限制爲每個產品的一個類別。這是一個觀察,而不是批評。 –