MySQIi seleccione conteo y ordene por conteo

My table looks like this (this is just an example):

id    name    title    time
1     name1   title1   1000
2     name1   title1   1001
3     name1   title1   1002
4     name2   title2   1003
5     name2   title2   1004
6     name3   title3   1005
7     name4   title4   1006
8     name4   title4   1007
9     name4   title4   1008
10    name4   title4   1009

I want to write a SQL statement to select the count of each name as well as the info related to it. Time is really a UNIX timestamp, but I just changed to make simple for this question.

// This is will get me the trending posts for only the last minute
$time_in_past = time() - 60;
    "SELECT COUNT(`id`) FROM `trending`........WHERE `time` < '$time_in_past'"

I want to results after fetching with while() statement in PHP to be like this:

name: name4 count: 4 title: title4
name: name1 count: 3 title: title1
name: name2 count: 2 title: title2
name: name3 count: 1 title: title3

I want them to be ordered by COUNT of each one while still getting 10 results (in this example there are only 4).

preguntado el 05 de mayo de 13 a las 10:05

I think I'm having difficulty understanding how you want 10 rows to be output, when in your example output you only have four. What should "still getting 10 results" look like? -

this is just an example, I have 100k records entered every minute. So there will be more than 4 outputs. Your sql query only showing 1 result. -

2 Respuestas

You need to group your results (by name), then join the result to your table again:

  SELECT   name, COUNT(*) AS cnt
  FROM     trending
  WHERE    time < ?
  GROUP BY name
) t
WHERE    time < ?

contestado el 05 de mayo de 13 a las 10:05

Looks like you could get away with a simple GROUP BY, algo como esto:

SELECT name, COUNT(*), title
FROM trending
GROUP BY name, title

Ya que tu name y title appear don't ever differ, grouping on those together will not give you any more rows. The ordering by DESC give you the count in a reverse order.

contestado el 05 de mayo de 13 a las 10:05

With the input table you have provided, that debemos show four rows, since I have grouped on two columns that have a variety of values. Can you show us where you are with a Violín SQL? If you can do that, edit it into your question as well as pinging me, so everyone can see the update. - la mitad

@Max: thanks for the update on your question, a Fiddle would be the best next step! - la mitad

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.