1

我有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)

谢谢,

4

1 回答 1

3

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

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

对于多个属性(基于知识更丰富的专家 Quassnoi 的博客文章):
我已经删除了产品表,因为这里不需要它

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

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

          UNION ALL
          SELECT <attributeid> AS att

正如预期的那样,查询的结果:

  attributename   numofproducts
       19"              1
      White             1
      <$100             1
于 2010-05-17T17:02:37.147 回答