在单个查询中是否有办法返回my_table where column_1 = "xxx"
行,如果它确实有结果,如果没有,则返回where column_2 = "xxx"
?
像select * from my_table where column_1 = "xxx" or column_2 = "xxx"
一样
但如果column_2= "xxx"
column_1 = "xxx"
此表有400M +行,因此请考虑性能
答案 0 :(得分:2)
您可以尝试此查询:
select t.*
from my_table t
where column_1 = 'xxx'
union all
select t.*
from my_table t
where column_2 = 'xxx' and
not exists (select 1 from my_table where column_1 = 'xxx');
如果您有column_1
的索引和column_2
上的另一个索引,那么这应该会有合理的效果。
如果你只想要一个值,你可以这样做:
select t.*
from (select t.*
from my_table t
where column_1 = 'xxx' or column_2 = 'xxx'
order by (case when column_1 = 'xxx' then 1 else 2 end)
) t
where rownum = 1;
这不会使用索引(至少不是很好),但只需对表进行一次扫描即可完成所需的操作。
答案 1 :(得分:2)
试试这个:
select *
from my_table
where (column_1 = "xxx"
and exists (select null from my_table where column_1 = "xxx"))
or (column_2 = "xxx"
and not exists (select null from my_table where column_1 = "xxx"))
答案 2 :(得分:0)
取决于我对您的问题的解释:
select decode( column1,'xxx',column1,column2 )
from my_table
where column1 = 'xxx' or column2 = 'xxx'