您在数据库中使用逗号分隔的字段。
这是一个巨大的 NONO,(My)SQL 并没有很好地处理这个问题。
如果每行中的值不超过 5 个,则可以执行以下操作:
代码错误警告
$month = mysql_real_escape_string($data['month']);
$year = mysql_real_escape_string($data['year']);
$sql = "SELECT
IFNULL(SUBSTRING_INDEX(result,',',1),0)
+ IFNULL(SUBSTRING_INDEX(result,',',2),0)
+ IFNULL(SUBSTRING_INDEX(result,',',3),0)
+ IFNULL(SUBSTRING_INDEX(result,',',4),0)
+ IFNULL(SUBSTRING_INDEX(result,',',5),0) as total_result
FROM mytable
WHERE `year` = '$year' AND `month` = '$month' ";
我不能 100% 确定 MySQL 是否会对“+”号感到满意,如果不是,您需要通过 REPLACE(IFNULL(SUBSTRING_INDEX(result,',',2),0),'+','') 过滤掉它们
见:
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substring-index
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace
重构数据库
我建议你改掉 CSV 的习惯,规范你的数据库。
将值放入不同的行(每行一个值)并将month和year列合并为一个,并添加一个名为id的auto_increment integer primary key列
您的表格将如下所示:
id result mydate
1 15 2011-01-01
2 13 2011-01-01
3 -15 2011-01-01
...
4875 -23 2011-08-28
现在您可以通过以下方式添加特定月份的结果总和:
$sql = "SELECT sum(result) as totalresult
FROM mytable
WHERE mydate BETWEEN '$startdate' AND '$enddate' ";
使用 between ... and 构造而不是函数 YEAR(mydate) and MONTH(mydate) 将允许 MySQL 使用索引来选择值。
您将列包装在一个函数中 MySQL 不能使用索引,这会大大降低速度。