Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

516
Visualizações
Why group by is not working properly? laravel

I'm currently using groupBy to group concatenated (book name and book_author). I'm intentionally using groupBy because I have other columns to get their average, and sum.

I initially used this code below. But it returning me an error.

Illuminate\Database\QueryException: SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated

Reference::select('*')
    ->selectRaw("CONCAT(book_name, ' ', book_author) AS book")
    ->groupBy('type');

If I add an id column inside groupBy, it does not returning an error. But it does not order, I still getting duplicate book.

Reference::select('*')
    ->selectRaw("CONCAT(book_name, ' ', book_author) AS book")
    ->groupBy(['id', 'type']);

Someone, how to achieve this properly?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

TLDR; When you use group by in strict mode, your selected fields must be aggregated fields.

Let's say you have two books with the same type.

book_name book_name type
First author 1
Second editor 1

When you group by type, those having the same type will be merged into one. So wich result will it be for CONCAT(book_name, ' ', book_author) ?

  • First author ?
  • Second editor ?
  • First editor ?
  • Second author?

The query doesnt gamble when strict mode is active, you need to aggregate the fields, for example LISTAGG(book_name , ',') is an aggregationg of the field book_name and result in 'first,second'.

If you disable the strict mode ('strict' => false,) in the file config/database.php, the result might be any of the 4 listed above as it is kinda random.

Other example for aggregation functions: SUM(), AVG(), COUNT()...

over 4 years ago · Santiago Trujillo Relatório

0

Please use the below link, as the solution is already available.

Solution Link.

Please check and you will find the solution.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda