Search code examples
mysqlmysql-error-1111

MYSQL INSERT INTO SELECT Statement Invalid use of group function


I have the following code:

select c.nome,(p.nome) as ultimo_produto 
from cliente c 
inner join compra cp on (c.cod_cli = cp.fk_cli) 
inner join produto p on(cp.fk_pod=p.cod_pro) 
where  datc >=max(cp.datc)  
group by c.nome;

want to get the customer's name and the name of the last product he bought, but the error invalid use of group function


Solution

  • select c.nome, p.nome as ultimo_produto 
    from cliente c 
    inner join compra cp on (c.cod_cli = cp.fk_cli) 
    inner join produto p on (cp.fk_pod=p.cod_pro) 
    inner join 
    (
      select cod_pro, max(datc) as mdatc
      from produto
      group by cod_pro
    ) x on x.cod_pro = p.cod_pro and x.mdatc = p.datc
    group by c.nome