Laravel: 有groupBy时列名重复
Laravel: Duplicate column name when there is a groupBy
为什么我的查询中有groupBy
子句会出现如下错误
Exception Message:\n\nSQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'id' (SQL: select count(*) as aggregate from (select * from `schools` inner join `dcp_batch_receives` on `dcp_batch_receives`.`school_id` = `schools`.`id` inner join `lib_districts` on `lib_districts`.`id` = `schools`.`district_id` inner join `lib_divisions` on `lib_divisions`.`id` = `lib_districts`.`division_id` group by `schools`.`id`) count_row_table)
这是我没有 groupBy
的查询,并且工作正常。
$schools = School::join('dcp_batch_receives', 'dcp_batch_receives.school_id', 'schools.id')
->join('lib_districts', 'lib_districts.id', '=', 'schools.district_id')
->join('lib_divisions', 'lib_divisions.id', '=', 'lib_districts.division_id');
当我添加 groupBy
时出现上述错误。
$schools = School::join('dcp_batch_receives', 'dcp_batch_receives.school_id', 'schools.id')
->join('lib_districts', 'lib_districts.id', '=', 'schools.district_id')
->join('lib_divisions', 'lib_divisions.id', '=', 'lib_districts.division_id')
->groupBy('schools.id');
也许您需要使用类似的方式指定所选字段。
->selectRaw("count(*) as name_count,schools.id")
在2个表中指定了列名id。
为什么我的查询中有groupBy
子句会出现如下错误
Exception Message:\n\nSQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'id' (SQL: select count(*) as aggregate from (select * from `schools` inner join `dcp_batch_receives` on `dcp_batch_receives`.`school_id` = `schools`.`id` inner join `lib_districts` on `lib_districts`.`id` = `schools`.`district_id` inner join `lib_divisions` on `lib_divisions`.`id` = `lib_districts`.`division_id` group by `schools`.`id`) count_row_table)
这是我没有 groupBy
的查询,并且工作正常。
$schools = School::join('dcp_batch_receives', 'dcp_batch_receives.school_id', 'schools.id')
->join('lib_districts', 'lib_districts.id', '=', 'schools.district_id')
->join('lib_divisions', 'lib_divisions.id', '=', 'lib_districts.division_id');
当我添加 groupBy
时出现上述错误。
$schools = School::join('dcp_batch_receives', 'dcp_batch_receives.school_id', 'schools.id')
->join('lib_districts', 'lib_districts.id', '=', 'schools.district_id')
->join('lib_divisions', 'lib_divisions.id', '=', 'lib_districts.division_id')
->groupBy('schools.id');
也许您需要使用类似的方式指定所选字段。
->selectRaw("count(*) as name_count,schools.id")
在2个表中指定了列名id。