0

我有两个 MySQL 表:

  • 属性(attributeid,名称)
  • 产品属性(productid、attributeid、displayvalue)

需要为每个名为“产品类型”的属性名称获取与此“产品类型”关联的所有其他属性。举个例子——属性表看起来像:

    attributeid  name
    1            A
    2            B
    3            Product Type
    4            D

productsattributes 表如下所示:

productid attributeid displayvalue
        1         3           FAN
        1         1           Brown
        1         2           Stand
        2         3           FAN
        2         4           D
        3         3           CAR
        3         4           imported

所以最终的结果应该是:

FAN (A,B, Product Type,D) 
CAR (Product Type, imported)

这是我的尝试:

  • 首先,我从产品属性中获取所有“显示值”:
SELECT DISTINCT displayvalue 
  FROM productsttributes 
 WHERE attributeid = 3;
  • 然后我遍历每个“显示值”以找到其他属性:
SELECT a.name 
 FROM attributes a 
 INNER JOIN productsattributes pa 
    ON pa.attributeid = a.attributeid AND productid in (
        SELECT productid 
        FROM productsttributes 
        WHERE dispalyvale =  '$displayvalue') 
 ORDER BY a.name;

问题是 productattributes 表有大约 700 万行,所以我的脚本需要永远......当然我不是在寻找 10 分钟的解决方案,但至少它会改善我的查询。

4

2 回答 2

1

我将从以下陈述开始:

ALTER TABLE attributes ADD CONSTRAINT p_attributes PRIMARY KEY (attributeid);
ALTER TABLE productsattributes ADD CONSTRAINT p_productsattributes
    PRIMARY KEY(productid, attributeid);
ANALYZE TABLE attributes, productsattributes;

这将确保所有重要字段都被索引。

查询可能如下所示(也在SQL Fiddle上):

SELECT trg.displayvalue,
       group_concat(a.name ORDER BY trg.productid, a.attributeid)
  FROM (
        SELECT t.productid,t.displayvalue
          FROM attributes a
          JOIN productsattributes t USING (attributeid)
         WHERE a.name = 'Product Type') AS trg
  JOIN productsattributes p ON p.productid = trg.productid
  JOIN attributes a ON a.attributeid = p.attributeid
 GROUP BY trg.displayvalue
 ORDER BY 1;

EXPLAIN在您的问题中包含您的输出和此查询。

于 2012-07-01T05:46:45.597 回答
0

试试这个 ::

Select displayvalue, attribute_name
from 
(Select 
product_id from productsattributes pa inner join attributes_table at on (pa.attributeid=at.id) where at.name=?) as productList
inner join  productsattributes pa2 on(pa2.product_id=productList.product_id)
inner join attributes_table at2 on (pa2.attributeid=at2.id)
于 2012-07-01T05:11:56.737 回答