Mysql查询按过滤器选择产品

时间:2014-03-19 09:58:29

标签: mysql sql

我尝试创建SELECT查询以通过某些过滤器获取产品。您可以在下面的屏幕上看到DB结构。 DB structure definitions - 产品类型,features - 产品功能(例如价格,尺寸,颜色),significations - 某些功能的价值,objects - 网站上的可用产品,{{ 1}} - 辅助表,可以建立多对多关系。

我在考虑所选过滤器的情况下使用php创建查询:

trans_obj2sign

内部查询返回对象的ID,其中含义接近所有过滤器。主查询返回所需的产品属性。<​​/ p>

问题是:

  1. 我可以重写此查询以更快地执行吗? (这个很重)
  2. 我应该添加哪些索引?
  3. 如何添加ORDER BY某些表示值。类似SELECT o.id, o.name, o.url, GROUP_CONCAT(f.name separator '--|||--') as feature_name, GROUP_CONCAT(f.title separator '--|||--') as feature_title, GROUP_CONCAT(s.value separator '--|||--') as signification_value FROM objects as o JOIN trans_obj2sign o2s ON o.id=o2s.object_id JOIN features f ON o2s.feature_id=f.id JOIN significations s ON o2s.signification_id=s.id WHERE o.id IN ( SELECT o2s.object_id FROM trans_obj2sign o2s JOIN significations s ON ( o2s.signification_id = s.id ) WHERE ( (s.id IN ("2", "43", "48", "55") AND s.feature =13) OR (s.id IN ("14", "23", "49", "52") AND s.feature =14) OR (s.value BETWEEN 0 AND 500 AND s.feature =17) ) GROUP BY o2s.object_id HAVING COUNT( o2s.object_id ) =3 ) GROUP BY o.id LIMIT 0, 50 (假装s.feature = 17是产品价格)

1 个答案:

答案 0 :(得分:1)

摆脱IN +子查询。只需将其移至FROM部分即可执行一次。

喜欢这个

SELECT o.id, o.name, o.url, GROUP_CONCAT(f.name separator '--|||--') as feature_name,        GROUP_CONCAT(f.title separator '--|||--') as feature_title, GROUP_CONCAT(s.value separator '--|||--') as signification_value
FROM objects as o
JOIN trans_obj2sign o2s ON o.id=o2s.object_id
JOIN features f ON o2s.feature_id=f.id
JOIN significations s ON o2s.signification_id=s.id
JOIN (
    SELECT o2s.object_id
    FROM trans_obj2sign o2s
    JOIN significations s ON ( o2s.signification_id = s.id ) 
    WHERE (
    (s.id IN ("2",  "43",  "48",  "55") AND s.feature =13)
    OR (s.id IN ("14",  "23",  "49",  "52") AND s.feature =14)
    OR (s.value BETWEEN 0 AND 500 AND s.feature =17)
    )
    GROUP BY o2s.object_id
    HAVING COUNT( o2s.object_id ) =3
) filtered on filtered.id=o.id
GROUP BY o.id
LIMIT 0, 50

为WHERE中使用的字段添加索引。

添加ORDER BY将查询放入FROM部分(作为子查询)并使用ORDER BY