现在我有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)它是获取带有值的属性,但我想知道一件事:是否有可能在table attributes中去掉'product_id'列,而不使用该列来获取属性和值?现在它是一大堆重复的属性,例如:
table attributes
-id 1
-attribute Weight
-product_id 1
-id 2
-attribute Weight
-product_id 2而我只想:
-id 1
-attribute Weight很抱歉我的英文,如果我的帖子中的某些部分需要更多的解释,请现在就让我来
发布于 2012-01-22 00:54:50
这取决于您是否希望您的属性是特定于产品的,但很明显,您不需要。此外,如果您的属性表中有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实际上,我会让它变得更简单:
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确保您有适当的索引。此外,选择产品is然后将其放入IN的方式也是一种糟糕的做法。
https://stackoverflow.com/questions/8954222
复制相似问题