【问题标题】:Searching products by specific attributes按特定属性搜索产品
【发布时间】:2016-11-01 13:35:17
【问题描述】:

我有一个小商店系统,现在我想选择一些具有特定属性和条件的产品。

这是我的设置:

表 XYZ:

  • product_id
  • attribute_id
  • attribute_group_id

所以现在我想选择所有属性 ID 为 1、3、5 和 7 而不是 9 和 2 的产品。

我怎样才能以一种简单的方式做到这一点,我的第一个想法是按产品 ID 和 group_concat 属性 ID 进行分组,并使用“拥有”来包含和排除我想要的属性 ID。

SELECT CONCAT('_',GROUP_CONCAT(attribute_id SEPARATOR '_'),'_') as attrs, 
       product_id
FROM my_table
GROUP BY product_id 
HAVING (attrs LIKE '%_1_%' 
        AND attrs LIKE '%_3_%' 
        AND attrs LIKE '%_5_%' 
        AND attrs LIKE '%_7_%')
AND (attrs NOT LIKE '%_2_%' 
    AND attrs NOT LIKE '%_9_%')

这可行,但有更好的解决方案,对吧?

【问题讨论】:

    标签: mysql relationship


    【解决方案1】:

    也许这会有所帮助?

    选择 product_id FROM 表_XYZ WHERE attribute_id IN (1,3,5,7);

    或者,如果您有更多 id 并且只排除少数几个:

    选择 product_id FROM 表_XYZ WHERE attribute_id NOT IN (2,9);

    【讨论】:

    • 问题是我想要具有所有这些属性的产品,您的查询将为我提供具有这些属性之一的每个产品。
    猜你喜欢
    • 1970-01-01
    • 2014-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多