我正在使用来自MySQL数据库的Highcharts创建图表,其中一个图表是一周内新列表的数量。我有一个名为ListDate的日期字段,它有一个索引。
想知道我是否可以(以及如果可以的话如何做)以及我是否应该在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 :(得分:1)
直到最近,才在MySQL上执行此操作,在最近发布的MySQL 5.7系列中添加了对虚拟列和索引的支持。
使用细节:http://mysqlserverteam.com/virtual-columns-and-effective-functional-indexes-in-innodb/
答案 1 :(得分: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)