【问题标题】:select attribute mysql选择属性mysql
【发布时间】:2010-05-17 16:36:34
【问题描述】:

我有mysql表:

**product (id,name)**
1  Samsung
2  Toshiba
3  Sony

**attribute (id,name,parentid)**
1 Size 0
2 19" 1
3 17" 1
4 15" 1
5 Color 0
6 White 5
7 Black 5
8 Price 0
9 <$100 8
10 $100-$300 8
11 >$300 8

**attribute2product (id,productid,attributeid)**
1 1 2
2 1 6
3 2 2
4 2 7
5 3 3
6 3 7
7 1 9
8 2 9
9 3 10

并将它们列为:

**Size**
-- 19" (2)
-- 17" (1)
-- 15" (0)

**Color**
-- White (1)
-- Black (2)

**Price**
-- <$100 (1)
-- $100-$300 (1)
-- >$300 (1)

请帮我 mysql 查询列出属性名称并计算该属性具有的数量产品。例如:选择尺寸19英寸(attribute.id 2)

**Size**
-- 19"

**Color**
-- White (1)
-- Black (1)

**Price**
-- <$100 (1)
-- $100-$300 (1)

这将查询 attribute2product >> 选择 productid >> 下一个查询以选择该 productid 的其他属性并显示属性名称,该属性名称现在具有的产品数......(如 Magento)

谢谢,

【问题讨论】:

  • 你能贴出列出它们的代码吗?这可能会有所帮助。
  • @Chris Chua:我想学习 mysql 查询(选择、加入、EAV 表..)列表,如 Magento 的产品属性过滤器。
  • 不应该WhiteBlack 有父ID 5

标签: filter product attributes mysql php


【解决方案1】:

我已修改查询。这应该是您基于更新的内容:

SELECT attribute.name AS attributename, COUNT(*) AS numofproducts FROM product 
  INNER JOIN attribute2product ON  attribute2product.productid = product.id
  INNER JOIN attribute ON attribute.id = attribute2product.attributeid
  WHERE product.id IN 
    (
     SELECT p.id FROM product AS p
     INNER JOIN attribute2product AS a2p ON a2p.productid = p.id
     WHERE a2p.attributeid = 2
    )
  GROUP BY attribute.id, attribute.name;

根据你上面我得到的数据:

  attributename   numofproducts
       19"              2
      White             1
      Black             1
      <$100             2

对于多个属性 (based a more knowledgeable expert Quassnoi's blog article):
我已删除产品表,因为这里不需要它

SELECT attribute.name AS attributename, COUNT(*) AS numofproducts
FROM attribute2product
  INNER JOIN attribute ON attribute.id = attribute2product.attributeid
  WHERE attribute2product.productid IN (
      SELECT o.productid
      FROM (
        SELECT productid 
        FROM (
          SELECT 2 AS att
          UNION ALL
          SELECT 6 AS att
          ) v
        JOIN attribute2product ON attributeid >= att AND attributeid <= att
        ) o
      GROUP BY o.productid
      HAVING COUNT(*) = 2
      )
  GROUP BY attribute.id, attribute.name

26 分别指的是19"WhiteCOUNT(*) = 2 是匹配 2 个属性。可以通过将以下内容附加到嵌套派生表来添加更多属性:

          UNION ALL
          SELECT <attributeid> AS att

正如预期的查询结果:

  attributename   numofproducts
       19"              1
      White             1
      <$100             1

【讨论】:

  • 第一个内部连接应该在attribute2product.productid = product.id
  • 使用查询选择属性时无法过滤,Chris Chua。它将显示我们选择的属性的名称。无论如何,我已经编辑了问题并尝试向您解释。请帮忙!
  • 我在我的代码中遗漏了一个ON,只是将它添加进去。它应该返回所选属性的名称以及具有该属性的产品数量。如果您仍然遇到问题,可以在这里发布您的结果吗?
  • 我的结果显示:Size -- 19" (2) Color -- 19" (2) Price -- 19" (2)
  • 我已根据您的新信息修改了我的答案。请看一下。 :)
猜你喜欢
  • 2014-07-16
  • 2015-06-21
  • 2012-09-08
  • 1970-01-01
  • 2010-10-19
  • 2012-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多