Display multiple records within a single MySQL [duplicate]

0

I have a question about assembling a select.

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

CurrentlyI'musingthissql:

selectp.descricao,(selectdescricaofromitemwhereitem.codigo=c.codigoItem)asitemsfromprodutopinnerjoincomposicaoconc.codigoProduto=p.codigoinnerjoinitemioni.codigo=c.codigoItemorderbyp.codigo

andtheresultlookslikethis:

Doyouhaveanyfunctiontosetagroupbyorwouldyouhavetomountastoredprocedure?AtfirstI'msolvingtheissueofdirectdisplayinJava,testingwhethereachiterationtheproductisthesame.

    
asked by anonymous 04.01.2019 / 20:43

2 answers

2

You can use MySQL's GROUP_CONCAT (expr) function.

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:

link

    
04.01.2019 / 21:04
2

You can do this by 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 GROUP_CONCAT function will group the results of the conditionals on the same line using a specified separator, in the case ", " (comma followed by space).

Result (tested in MySQL-Front):

  

Note: To not seem like a copy, I was writing the response when the other one was published. As both were similar but with a construction and   a somewhat different result, I decided to keep this active response as an option.

    
04.01.2019 / 21:06