EAV查询和表格

时间:2012-01-21 15:36:46

标签: mysql database entity-attribute-value querying

现在我有4张桌子:

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)

它获得了带有值的属性,但我想知道一件事: 如果可以删除'product_id'中的table attributes列并获取没有该列的属性和值?现在它是一大堆重复属性,例如:

table attributes 
-id 1
-attribute Weight
-product_id 1

-id 2
-attribute Weight
-product_id 2

虽然我只想:

-id 1
-attribute Weight

对不起我的英语,如果我的帖子的某些部分需要更多解释请立即让我

1 个答案:

答案 0 :(得分:0)

这取决于您是否希望您的属性是特定于产品的,但显然,您不需要。此外,如果在属性表中有product_id,则不需要value表中的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来实现它,这是一种不好的做法。