MySQIi select count and order by count

2019-07-21 15:11发布

问题:

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;
$mysqli->query(
    "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).

回答1:

Looks like you could get away with a simple GROUP BY, something like this:

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

Since your name and 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.



回答2:

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

SELECT * FROM trending NATURAL JOIN (
  SELECT   name, COUNT(*) AS cnt
  FROM     trending
  WHERE    time < ?
  GROUP BY name
) t
WHERE    time < ?
ORDER BY t.cnt DESC