2015-11-26 72 views
0
添加索引的周日期中

我使用Highcharts从MySQL数据库和一个图表中创建图表是在一周新上市的数量。我有名为ListDate的日期字段,它有一个索引。在MySQL

想知道我是否可以(以及如何做到这一点),如果我应该添加一个索引到ListDate的一周。

这里是我的代码,如果它有助于:

$Week = 1; 
while($Week <= 53) 
    { 
    $NumListings = $wpdb->get_var("SELECT COUNT(MLSNumber) 
    FROM IRES WHERE 
    City = \"$City\" AND 
    WEEK(ListDate,3) = $Week AND 
    YEAR(ListDate) = $ThisYear AND 
    Category=1 AND 
    TotalUnits < 2"); 

    if($NumListings != "" AND $NumListings > 0 AND !(date("Y") == $ThisYear AND date("W") == $Week)) 
     { 
     $Content .= "    [".$Week.", ".$NumListings."],\n"; 
     } 

    $Week++; 
    } 
+0

我不知道如果MySQL支持函数索引;如果是这样,你可以简单地'CREATE INDEX week_of_listing ON ires(WEEK(listdate,3));'如果没有,最糟糕的结果是一个错误信息。 ;) –

+0

是的,这给了我一个错误。 –

+0

您是否在寻找除本周以外的特定城市每年每周的新房源(类别= 1)? – JRD

回答

1

代替执行52个查询,我会运行一个查询来收集数据。

SELECT WEEK(ListDate,3) AS week, COUNT(MLSNumber) as new_listings 
FROM IRES 
WHERE City = \"$City\" 
AND ListDate between 
     -- The 1st of the year through the last day of the year. 
     str_to_date(concat('01-01-', '$ThisYear'),'%m-%d-%Y') and 
     str_to_date(concat('12-31-', '$ThisYear'),'%m-%d-%Y') 
     -- If $ThisYear is the current year, limit to the most recent full week. 
AND ListDate <= curdate() - interval weekday(curdate()) day 
AND Category = 1 
AND TotalUnits < 2 
GROUP BY WEEK(ListDate,3); 

你可以尝试不同的索引,看看有什么效果最好,如

index(City) 
index(City,Category) 
index(City,ListDate,Category) 
index(ListDate) 
index(ListDate,Category) 
index(ListDate,City,Category)