【问题标题】:sql filter on multiple columnssql过滤多列
【发布时间】:2021-03-16 08:11:54
【问题描述】:

树:

id name
1  apple
2  aspen

树属性类别:

id categorie
1  leafColour
2  trunkColour

树属性:

id tree_id attribute tree_attribute_categorie_id
1  1       brown     1
2  1       brown     2
3  2       green     1
4  2       brown     2

sql 语句如何过滤​​如下(属性和 tree_attribute_categorie_id):

[[brown and 1] OR [red and 1]] AND [[brown and 2] OR [green and 2]] = return apple tree
[[brown and 1] OR [green and 1]] AND [[brown and 2] OR [green and 2]] = returns both trees

【问题讨论】:

    标签: mysql sql inner-join aggregate-functions having-clause


    【解决方案1】:

    您可以使用group byhaving

    select t.*
    from tree t
    inner join treeattributes ta on ta.tree_id = t.id
    group by t.id
    having max(ta.tree_attribute_categorie_id = 1 and ta.attribute in ('brown', 'red')) = 1
       and max(ta.tree_attribute_categorie_id = 2 and ta.attribute in ('brown', 'green')) = 1
    

    这符合您问题中的第一个过滤器规范。第二个规范的 having 子句如下所示:

    having max(ta.tree_attribute_categorie_id = 1 and ta.attribute in ('brown', 'green')) = 1
       and max(ta.tree_attribute_categorie_id = 2 and ta.attribute in ('brown', 'green')) = 1
    

    如果您想按属性名称而不是按属性 id 进行过滤,您可以再添加一个连接,并调整 having 子句:

    select t.*
    from tree t
    inner join treeattributes ta on ta.tree_id = t.id
    inner join treeattributecategori tag on tag.id = ta.tree_attribute_categorie_i
    group by t.id
    having max(tag.categorie = 'leafColour' and ta.attribute in ('brown', 'red')) = 1
       and max(tag.categorie = 'trunkColour' and ta.attribute in ('brown', 'green')) = 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多