【问题标题】:conditions (where) mysql条件(在哪里)mysql
【发布时间】:2011-07-15 16:23:57
【问题描述】:

餐桌产品:

id|name
-------
1 |computer
2 |microwave
3 |transl

表product_features:

feature          | id_product | feature_value
------------------------------------
count_of_buttons | 1          | 1
count_of_buttons | 2          | 2
count_of_buttons | 3          | 1
color            | 1          | white
color            | 2          | white
color            | 3          | black

请问,如何一键搞定所有白色产品? 非常感谢!

【问题讨论】:

    标签: mysql join where


    【解决方案1】:
    select product.*
    
    from product
      join product_features as buttons
        on buttons.id_product = product.id
      join product_features as color
        on color.id_product = product.id
    
    where buttons.feature_value = '1'
      and buttons.feature = 'count_of_buttons'
    
      and color.feature_value = 'white'
      and color.feature = 'color';
    

    【讨论】:

      【解决方案2】:
      select
          p.id
          p.name
      from
          products p
          join (select * from product_features where feature = 'color') colors on (p.id=colors.id_product)
          join (select * from product_features where feature = 'count_of_buttons') buttons on (p.id=buttons.id_product)
      where
          colors.feature_value = 'white'
          and buttons.feature_value = 1
      

      您可能会考虑重新组织 product_features 表,以便每个功能都有一个单独的列(即 color 列和 count_of_buttons 列),以便每个产品都有一行。事实上,它可能都在 products 表中。

      【讨论】:

      • product_features 表是 EAV(实体-属性-值)方法的一个示例。不需要窗口函数。使用这种方法,查询通常需要多次连接(到同一个表)。
      • 这种方法会不会很昂贵,尤其是对于大表? RE 窗口函数一开始似乎很有意义,但现在我想不出它们会有什么用——编辑答案。
      • EAV 的问题不在于 JOIN 的成本。在一个查询中有许多连接可能会很慢,但使用索引可能会非常快。还有其他问题,例如您必须在同一列中存储许多不同的数据类型。还有一些很难(如果不是不可能)强制执行的参照完整性约束。
      • 我们如何防止出现'count_of_buttons', 'purple''color', '73' 的行?
      【解决方案3】:

      选择 p.id FROM 产品 p 加入 product_features pf ON p.id = pf.id 其中 pf.feature_value = 'white' AND pf.count_of_buttons = 1

      【讨论】:

      • 不起作用,因为colorcount_of_buttons 是同一列中的不同行,而不是同一行中的不同列。
      【解决方案4】:
      select p.id, p.name from products p inner join product_features ON p.id=id_product where feature_value='white' and feature='color' and count_of_buttons=1
      

      【讨论】:

      • OP 要求只有一个按钮的白色产品。这只提供白色产品。
      • @ypercube 自我发表评论以来已对其进行了编辑。不过还是不行。
      猜你喜欢
      • 2012-04-01
      • 2013-07-30
      • 2021-05-07
      • 2016-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-06
      • 2011-06-01
      相关资源
      最近更新 更多