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

How to refactor a SQL query with multiple OR statements for better performance?

使用 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) 上的索引。