Query Builder原生子查询运行报错1064SQL语法错误,写法是否正确?
问题排查结论
你写的子查询逻辑本身是符合MySQL语法规则的,出现1064语法错误可从以下几个方向排查:
- 检查
DB::raw内多行字符串拼接是否引入了异常字符:你当前把子查询拆成多行写在双引号内,PHP解析时可能带入多余的换行/不可见字符,导致SQL拼接后语法断裂。可以先将子查询内容合并为单行测试:DB::raw("(SELECT grievance_history.status FROM grievance_history WHERE grievance_history.grievance_id = grievance_redress_info.id ORDER BY grievance_history.id DESC LIMIT 1) AS current_status") - 检查涉及的表名、字段名是否拼写错误,是否使用了SQL保留字未做转义:比如
status在部分SQL模式下属于保留字,如果开启了严格模式可以用反引号包裹字段名:DB::raw("(SELECT grievance_history.`status` FROM grievance_history WHERE grievance_history.grievance_id = grievance_redress_info.id ORDER BY grievance_history.id DESC LIMIT 1) AS current_status")
更稳妥的替代写法
推荐使用Laravel查询构造器原生的selectSub方法实现相同逻辑,无需手写原生SQL,完全避免语法拼接错误:
$result = DB::table('grievance_redress_info') ->select( 'complainer_name', 'phone', 'complaint_date', 'address', 'complaintSub.name_en', 'resolve_action_date' ) ->selectSub(function ($query) { $query->from('grievance_history') ->select('status') ->whereColumn('grievance_history.grievance_id', 'grievance_redress_info.id') ->orderByDesc('id') ->take(1); }, 'current_status') ->leftJoin('common_labels AS complaintSub', 'grievance_redress_info.complaint_subject_id', '=', 'complaintSub.id') ->get();
内容的提问来源于stack exchange,提问作者simpson
相关产品推荐
相关产品推荐

