sql 过滤多列
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
树:
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