How to sort from what has more records to what has less

2

I have a table where id_produto and ip will be stored. I'll mount a "module" where the system will pull some of the products that have had the most visits, so what I need to do is pull the products that have the most records in the table, from the highest to the lowest. How can I do this using PHP / MySQL?

    
asked by anonymous 19.04.2016 / 04:19

3 answers

1

You can use count() .

This would look like this:

SELECT *, count(ip) AS contagem
FROM tabela
GROUP BY id_produto
ORDER BY contagem DESC

In this way you will count ip , declaring the name of 'count'.
The number of ip by id_produto will be sorted in DESC , in addition you can show it since it is in SELECT . :)

    
19.04.2016 / 12:29
0

Our friend your question was a little broad, but I created a select that will help you. Thinking about a structure you would have two tables

  • products (product_id, name, description, etc.)
  • visual_products (product_id, ip)

This select returns the products by ordered by the number of DESC views

SELECT produtos.*, count(produtos_visualizados.*) AS visualizacao 
FROM produtos
left join produtos_visualizados ON produtos.id_produto = produtos_visualizados.id_produto
group by produtos.id_produto
order by visualizacao DESC

Now you only have to enter this table every time a product is accessed, and create a model to retrieve this data.

    
19.04.2016 / 05:01
0

In SQL, for you to bring these "some products", you first need to define how many, in the example below, I considered the top 10:

SELECT prd.id_produto,
       rel.ip 
       COUNT(prd.id_produto) AS total_produtos
FROM TABELA_PRODUTO prd
INNER JOIN  TABELA_REL_PRODUTO_TOTAL rel on(rel.id_produto=prd.id_produto)
GROUP prd.id_produto ORDER BY total_produtos desc LIMIT 0,10; 

Now if in this relational table, you will have the count directly, it would have to look something like this:

SELECT prd.id_produto,
       rel.ip, 
       rel.total
FROM TABELA_PRODUTO prd
INNER JOIN TABELA_REL_PRODUTO_TOTAL rel on(rel.id_produto=prd.id_produto)
GROUP prd.id_produto ORDER BY rel.total desc LIMIT 0,10; 
    
19.04.2016 / 14:10