Sort result of a query with JOIN based on the number of records of one of the tables

1

Assuming I have two tables in my database ( pedidos and pedidos_itens ) how can I get the data from the orders sorted by the orders that contain the most items?

I have tried to do a Right Join , but I do not know what to use in the order by clause, since my goal is to sort by the number of records in the% .

    
asked by anonymous 17.11.2016 / 13:07

1 answer

3

Try this:

SELECT
  COUNT(pi.*) AS itens,
  p.id AS id,
  p.descricao AS desc
FROM pedido p
  INNER JOIN pedido_itens pi ON
    pi.id_pedido = p.id
GROUP BY id, desc
ORDER BY itens ASC

The idea is to give COUNT of the amount of items returned to the request, group the registry data in GROUP BY and ORDER BY by COUNT .

    
17.11.2016 / 13:09