简体   繁体   English

计算SQL表中每个不同值的数量

[英]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) 我想算一下,有多少人看过文章a和多少人b(我有很多文章,我想获得最受欢迎的十大文章)

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? 因此,有没有一种简单的方法可以通过SQL进行此操作,目前我是用php数组完成的,我要获取数组中所有不同的行,然后获取每个数组值有多少行,然后进行排序数组并回显前10个,但这是太多查询的方式,我想知道,是否有办法用1个查询来做到这一点?

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. 该查询将返回10条文章,即使根本没有10条文章具有视图。 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. 但是,第一个查询的优点是您还可以将'a'其他字段添加到查询结果中,例如标题。 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. 因此,此单个查询实际上可以返回生成完整的前10个列表所需的所有信息,而第二个查询仅提供ID列表。

It is easy to do with sql grouping. 使用sql分组很容易。

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

Obviously, you will need to change the tables and fields. 显然,您将需要更改表和字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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