Skrevet av Emne: Mysql: Optimize OR clauses using UNION  (Lest 2146 ganger)

ATC

  • Gjest
Mysql: Optimize OR clauses using UNION
« på: 27. ſeptember 2008, 18:24 pm »
  • [applaud]0
  • [smite]0
  • On large tables, a query such as the following one will optimize poorly and use the index for the OR'ed column inefficiently:

    SELECT * FROM syslog
    WHERE ( prog = 'sshd' OR prog = 'sshd(pam_unix)' )
    AND   user = 'floyd'
    ORDER BY timestamp DESC
    LIMIT 10

    The result is surprisingly poor performance, even if both the "prog" and "user" columns are properly indexed.



    ATC

    • Gjest
    [Solved] Mysql: Optimize OR clauses using UNION
    « Svar #1 på: 27. ſeptember 2008, 18:24 pm »
  • [applaud]0
  • [smite]0
  • Rewrite using UNION:

    (
      SELECT * FROM syslog
      WHERE prog = 'sshd'
      AND   user = 'floyd'
    ) UNION (
      SELECT * FROM syslog
      WHERE prog = 'sshd(pam_unix)'
      AND   user = 'floyd'
    )
    ORDER BY timestamp DESC
    LIMIT 10

    The resulting dataset is exactly the same, but now you're telling MySQL explicitly to look for two distinct combinations of data. This lets MySQL use the index for "prog" more efficiently and the result is a significant performance boost.

    Note that UNION was implemented in MySQL 4.x