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

如何使用多个OR语句重构SQL查询以获得更好的性能?,sql,mariadb,query-optimization,hql,where-clause,Sql,Mariadb,Query Optimization,Hql,Where Clause,使用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 .......

使用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) ) 
在子句中使用
进行重构不是一种选择,因为它会产生笛卡尔积

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\u字段,date\u字段,id)

上的索引,您正在使用哪个dbms?您是如何为表编制索引的?如果你没有,那就从这里开始。看见您可能需要在代码字段+日期字段上建立索引。有时,先将这些行加载到表中,然后联接会更快。@jarlh MariaDB@AndyLester除了主键上的索引外,我在代码字段+日期字段及其相关索引上有一个唯一的键,有没有办法利用它,或者它只是帮助Hibernate更快地执行查询?答案很好!使用元组相等,对于相同数量的组合,查询运行时间不到一半。