代码之家  ›  专栏  ›  技术社区  ›  Christos Karapapas

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

  •  0
  • Christos Karapapas  · 技术社区  · 6 年前

    使用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来改进这个查询?

    1 回复  |  直到 6 年前
        1
  •  1
  •   GMB    6 年前

    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) .