我有这个工作的mysql查询
select niv.*, count(en.estudiante) as inscritos
from niveles as niv
inner join estudiante_nivel as en on en.nivel = niv.nivel_id
GROUP by niv.nivel_id
having (niv.estudiantes - inscritos) > 0
也在Laravel雄辩中
$niveles = $colegio->_niveles()
->select('niveles.*', DB::raw("COUNT(en.estudiante) AS total"))
->join('estudiante_nivel as en', 'en.nivel', '=', 'niveles.nivel_id')
->groupBy('niveles.nivel_id')
->havingRaw("(niveles.estudiantes - total) > 0")
->orderBy('nombre')
->get();
但是我得到了这个错误
QueryException in Connection.php line 647:
SQLSTATE[42000]: Syntax error or access violation: 1055 'kidsbook2.niveles.nombre' isn't in GROUP BY (SQL: select `niveles`.*, COUNT(en.estudiante) AS total from `niveles` inner join `estudiante_nivel` as `en` on `en`.`nivel` = `niveles`.`nivel_id` where `niveles`.`colegio` = 4 and `niveles`.`colegio` is not null group by `niveles`.`nivel_id` having (niveles.estudiantes - total) > 0 order by `nombre` asc)
我一直在读,我必须将总字段放在组内,但我仍然会收到错误。
有什么问题?任何人都可以帮助我吗?
表定义
CREATE TABLE `niveles` (
`nivel_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`nombre` VARCHAR(50) NOT NULL,
`seccion` VARCHAR(20) NOT NULL,
`estudiantes` INT(10) NOT NULL,
`maestros` INT(10) UNSIGNED NOT NULL,
`colegio` INT(10) UNSIGNED NOT NULL,
`created_at` TIMESTAMP NULL DEFAULT NULL,
`updated_at` TIMESTAMP NULL DEFAULT NULL,
PRIMARY KEY (`nivel_id`),
INDEX `nivel_colegio_idx` (`colegio`),
CONSTRAINT `nivel_colegio` FOREIGN KEY (`colegio`) REFERENCES `colegios` (`colegio_id`) ON UPDATE CASCADE ON DELETE CASCADE
)
CREATE TABLE `estudiante_nivel` (
`en_id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`estudiante` INT(10) UNSIGNED NOT NULL,
`nivel` INT(10) UNSIGNED NOT NULL,
`created_at` TIMESTAMP NULL DEFAULT NULL,
`updated_at` TIMESTAMP NULL DEFAULT NULL,
PRIMARY KEY (`en_id`),
INDEX `en_estudiante_idx` (`estudiante`),
INDEX `en_nivel_idx` (`nivel`),
CONSTRAINT `en_estudiante` FOREIGN KEY (`estudiante`) REFERENCES `estudiantes` (`estudiante_id`) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT `en_nivel` FOREIGN KEY (`nivel`) REFERENCES `niveles` (`nivel_id`) ON UPDATE CASCADE ON DELETE CASCADE
)