简体   繁体   中英

Count how many of each distinct value is in SQL table

I am wondering if there is easy way to get number of how many rows of distinct values I have (bad explanation, I know)

Example: I have table, which registers views for my blog articles. I want to count, how many have viewed article a and how many b (I have many articles, I want to get top 10 most viewed articles)

So is there an easy way to get this with SQL, at the moment I did it with php arrays, I'm getting all the distinct rows in array, then I get how many of rows there is for every array value, then I sort array and echo first 10, but that is way too many queries, I was wondering, if there is way to do this with 1 query?

select
  a.article_id,
  a.title,
  a.date,

  /* Make sure to count a relevant view from the *views* table. 
  -- This makes sure that count returns 0 instead of 1 when
  -- the article isn't viewed yet. */
  count(v.article_id) as viewcount

from
  Article a

  /* Using left join here, to also include articles that are not viewed at all.
  -- You can change this to an inner join if you don't want to include those. */
  left join ArticleView v on v.article_id = a.article_id

group by
  /* Group by article id, so count() actually counts per article. */
  a.article_id

order by
  /* Place the best viewed articles on top. */
  count(v.article_id) desc

  /* And return only 10 articles at most. */
limit 10

This query will return 10 articles, even if there are no 10 that have views at all. If you want to only return articles that actually have views, and you don't need other fields from the article table, you can simplify the query a little:

select
  v.article_id,
  count(v.article_id) as viewcount
from
  ArticleView v
group by
  v.article_id
order by
  count(v.article_id) desc
limit 10

But the advantage of the first query is that you can also add other fields of 'a' to your query result, like the title. So this single query can actually return all the information you need to generate the entire top-10 list, while the second only provides a list of ids.

It is easy to do with sql grouping.

select articleid, count(*) from view_table group by articled

Obviously, you will need to change the tables and fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM