我有两个具有一对多关系的表,像这样:
MY_TABLE(ID, VALUE)
MY_TABLE_ATTRIBUTE(ID, MY_TABLE_ID, NAME, VALUE)
我想检查MY_TABLE中是否有具有特定属性的记录。
此查询可能会解释我在做什么:
select 1
from MY_TABLE mt
where exists (select 1
from MY_TABLE_ATTRIBUTE mta
where mta.my_table_id = mt.id
and (mta.name = 'attributeName1' and mta.value = 'attributeValue1'))
and exists (select 1
from MY_TABLE_ATTRIBUTE mta
where mta.my_table_id = mt.id
and (mta.name = 'attributeName2' and mta.value = 'attributeValue2'))
and exists ...
.
.
.
我的问题是,是否有更好(更快)的方法来检查该存在。
预先感谢
答案 0 :(得分:1)
您的查询很好。为了提高性能,您需要以下索引:
create index idx_my_table_attribute_3 on my_table_attribute(my_table_id, name, value);
实际上,有了这个索引,您的代码可能是在Oracle中实现此逻辑的最快方法。
答案 1 :(得分:0)
尝试以下重写:
select * from MY_TABLE mt
where exists (select 1 from MY_TABLE_ATTRIBUTE mta
where mta.my_table_id = mt.id
and(
(mta.name = 'attributeName1' and mta.value = 'attributeValue1')
OR (mta.name = 'attributeName2' and mta.value = 'attributeValue2')
OR ....
)
或
select * from MY_TABLE mt
where mt.id in (select mta.my_table_id from MY_TABLE_ATTRIBUTE mta
where
(mta.name = 'attributeName1' and mta.value = 'attributeValue1')
OR (mta.name = 'attributeName2' and mta.value = 'attributeValue2')
OR ....
)
如果这些列的基数非常高,则(名称,值)的索引可能会有所帮助。