0

我想知道是否有简单的方法来获取我有多少行不同的值(不好的解释,我知道)

示例:我有一个表格,它为我的博客文章注册视图。我想数一下,有多少人看过文章 a 和多少篇文章 b(我有很多文章,我想获得前 10 篇浏览次数最多的文章)

那么有没有一种简单的方法可以使用 SQL 来获取它,目前我使用 php 数组进行操作,我得到了数组中所有不同的行,然后我得到每个数组值有多少行,然后我排序数组和前 10 个回显,但是查询太多了,我想知道,是否有办法用 1 个查询来做到这一点?

4

2 回答 2

2
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

此查询将返回 10 篇文章,即使根本没有 10 篇有浏览量。如果您只想返回实际有视图的文章,并且不需要文章表中的其他字段,则可以稍微简化查询:

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

但是第一个查询的好处是你还可以'a'在查询结果中添加其他字段,比如标题。所以这个单一的查询实际上可以返回生成整个 top-10 列表所需的所有信息,而第二个只提供一个 id 列表。

于 2013-10-07T20:57:32.077 回答
1

使用 sql 分组很容易。

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

显然,您将需要更改表和字段。

于 2013-10-07T20:57:37.943 回答