[英]sql filter on multiple columns
树:
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
您可以使用group by
并having
:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.