简体   繁体   English

需要优化SQL查询

[英]Need to optimize a SQL Query

Here is the where clause of the SQL. 这是SQL的where子句。 when I'm removing this part, it's taking 3 mins to execute, with this one it's taking more than 15 mins there are almost 9000 records in DB 当我删除这个部分时,它需要3分钟才能执行,这个需要花费超过15分钟的时间,数据库中有近9000条记录

WHERE username = 'xyz' AND 
( 
    ( acceptedfordeliverytime BETWEEN '2012-9-1' AND '2013-1-29' ) 
    OR 
    ( 
        YEAR(acceptedfordeliverytime) = YEAR('2013-1-29') 
        AND 
        MONTH(acceptedfordeliverytime) = MONTH('2013-1-29') 
        AND 
        DAY(acceptedfordeliverytime) = DAY('2013-1-29')
    ) 
    OR 
    ( 
        YEAR(acceptedfordeliverytime) = YEAR('2012-9-1') 
        AND 
        MONTH(acceptedfordeliverytime) = MONTH('2012-9-1') 
        AND 
        DAY(acceptedfordeliverytime) = DAY('2012-9-1') 
    )
)

Why don't you just use: 你为什么不用它:

WHERE username = 'xyz' AND 
      (acceptedfordeliverytime >= '2012-09-01' AND 
       acceptedfordeliverytime < '2013-01-30'
      ) 

This will also allow an index on (username, acceptedfordeliverytime) to be used when executing the query. 这还将允许在执行查询时使用索引(username, acceptedfordeliverytime)

I think this will give you the same results. 我想这会给你相同的结果。 and also make an index for column acceptedfordeliverytime to speed up searching. 并且还为已接受的列提供索引以加快搜索速度。

WHERE username = 'xyz' AND acceptedfordeliverytime BETWEEN '2012-9-1' AND '2013-1-29'

Isn't BETWEEN inclusive? 不包含BETWEEN吗? This would mean that you don't need all the extra clauses (that check for the first and last date in a VERY elaborate way). 这意味着您不需要所有额外的条款(以非常精细的方式检查第一个和最后一个日期)。 I believe your query would return the same result if you just did: 我相信你的查询会返回相同的结果,如果你刚才:

WHERE username = 'xyz' AND 
( 
    acceptedfordeliverytime BETWEEN '2012-9-1' AND '2013-1-29'
)

Your both OR part is unnecessary. 你的两个OR部分是不必要的。

when you use 当你使用

acceptedfordeliverytime  Between '2012-9-1' AND '2013-1-29'

It used both date included so OR part is not needed. 它使用了两个日期,因此不需要部分。 if you have date and time in your database then you can convert it into date like this 如果您的数据库中有日期和时间,那么您可以将其转换为这样的日期

CAST(acceptedfordeliverytime as date)  Between '2012-9-1' AND '2013-1-29'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM