如何用多个OR语句重构SQL查询以获得更好的性能



使用MariaDB。

查询如下:

select  * from table    
where  id > 0  and
( code_field = :code1 and date_field = date(:date1) )  or  
( code_field = :code2 and date_field = date(:date2) )  or  
( code_field = :code3 and date_field = date(:date3) )  or  
...................................................... -- a few thousands combinations  
( code_field = :codeX and date_field = date(:dateX) ) 

使用IN子句重构不是一种选择,因为它确实会产生笛卡尔乘积。

select  * from table    
where  id > 0  and
code_field in (:code1, :code2) and
date_field in (:date1, :date2)

有没有一种方法可以改进这个查询,无论是使用本机SQL还是使用HQL?

MariaDB理解元组相等,因此可以将条件写成:

where 
id > 0 
and (code_field, date_field) in (
(:code1, date(:date1)),
(:code2, date(:date2)),
(:code3, date(:date3)),
...
(:codeN, date(:dateN))
)

这可能会利用(code_field, date_field, id)上的索引。

最新更新