如何修复错误“CDbCommand ... SQLSTATE [42000]:语法错误或访问冲突:1064”

时间:2014-09-01 06:13:20

标签: php mysql yii

使用sql请求时出现此错误

$query = "SELECT SUM ".$fields."
                  FROM tbl_report all_months
                  ".$joins."
                  WHERE all_months.date > '$from_date' 
                        AND all_months.date < '$to_date' GROUP BY fio";

但是运营商Distinct可以运作

$query = "SELECT DISTINCT ".$fields."
                  FROM tbl_report all_months
                  ".$joins."
                  WHERE all_months.date > '$from_date' 
                        AND all_months.date < '$to_date' GROUP BY fio";

1 个答案:

答案 0 :(得分:2)

在mysql sum()上使用开括号和右括号:

$query = "SELECT SUM (".$fields.") AS result_value

注意:正如hanky在评论中所说,如果$fields的值包含以逗号分隔的列名列表,它可能无法正常工作。

如果确实如此,那么您需要使用+代替,

$fields = str_replace(',', '+', $fields);