View multiple records within one in Mysql

Asked

Viewed 426 times

-1

I have a question as to the mounting of a select.

I have 3 tables that relate M:N as follows:

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

inserir a descrição da imagem aqui

Currently I am using this sql:

select p.descricao,
       (select descricao from item where item.codigo = c.codigoItem) as items  
from produto p inner join composicao c on c.codigoProduto = p.codigo 
inner join item i on i.codigo = c.codigoItem 
order by p.codigo

and the result comes like this:

inserir a descrição da imagem aqui

Beauty, however it would be possible to make an output as in the image below direct by sql?

Has some function to define a group by or you’d have to ride a stored Procedure? At first I’m solving the issue of direct display in Java, testing if at each iteration the product is the same.

inserir a descrição da imagem aqui

  • Try this https://stackoverflow.com/questions/276927/can-i-concatenate-multiple-mysql-rows-into-one-field

  • Great @Wictorchaves, following the tips that are in this link that you passed worked. Now have to mark as solved? Put the answer?

2 answers

2


You can use the function GROUP_CONCAT(expr) mysql.

Your SQL query would look like this:

select p.descricao,
  GROUP_CONCAT( (select descricao from item where item.codigo = c.codigoItem) SEPARATOR ',' )
from produto p inner join composicao c on c.codigoProduto = p.codigo 
inner join item i on i.codigo = c.codigoItem 
group by p.descricao
order by p.codigo

You can see more about the function and its details in the documentation:

https://dev.mysql.com/doc/refman/8.0/en/group-by-functions.html#function_group-Concat

  • Thank you very much @Lucas for the answer and the attention! I really didn’t know about the existence of the GROUP_CONCAT function!

2

You can do it this way, using GROUP_CONCAT:

select p.descricao, 
       (select
       GROUP_CONCAT(i.descricao  separator ', ')
       from item where item.codigo = c.codigoItem)
       as items  
from produto p inner join composicao c on c.codigoProduto = p.codigo 
inner join item i on i.codigo = c.codigoItem 
group by p.descricao
order by p.codigo

The function GROUP_CONCAT will group the conditional results in the same row using a specified separator, in the case ", " (comma followed by space).

Result (tested in Mysql-Front):

inserir a descrição da imagem aqui

Obs.: not to sound like a copy, I was writing the answer when the other one was published. As they both looked alike but with a construction and a slightly different result, I decided to keep this response active as an option.

  • Great @Sam! I really appreciate the attention given to my problem! Really I was unaware of the GROUP_CONCAT function. It worked to solve!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.