mysql - 显示 mySQL 数据库中唯一记录的总数

标签 mysql ruby-on-rails ruby

我正在尝试完成一项作业,其中 mySQL 数据库中有 100 万条记录,每条记录都有一个 URL 和一个引用 URL(当然还有一个 ID)。作业的部分目标是通过“ View ”显示出现次数最多的 5 个 URL(又名:每个 URL 成为数据库中记录的频率)

我相信我已经非常接近了,因为目前我已经显示了前 5 个 URL,但我的问题是我只能获取要显示的记录总数(1000000 条或每个连续 URL 的浏览量)在同一行)

我的 Controller 代码如下所示: (该 URL 是数据库中唯一出现的 URL)

@url = Url.where({ url: ["http://apple.com", "https://apple.com", "https://www.apple.com", "http://developer.apple.com", "http://en.wikipedia.org", "http://opensource.org"]}).group("url").limit(5).order(:created_at)
@viewcount = @url.count

我的 View 代码如下所示:

<% @url.each do |url| %>
<%= url.url %> Views: <%= @viewcount %>
<% end %>

这是当前的显示方式:

1st URL Views: {"1st URL"=>166420, "2nd URL"=>166182, "3rd URL"=>166804, "4th URL"=>167351, "5th URL"=>165933}

2nd URL Views: {"1st URL"=>166420, "2nd URL"=>166182, "3rd URL"=>166804, "4th URL"=>167351, "5th URL"=>165933}

3rd URL Views: {"1st URL"=>166420, "2nd URL"=>166182, "3rd URL"=>166804, "4th URL"=>167351, "5th URL"=>165933}

4th URL Views: {"1st URL"=>166420, "2nd URL"=>166182, "3rd URL"=>166804, "4th URL"=>167351, "5th URL"=>165933}

5th URL Views: {"1st URL"=>166420, "2nd URL"=>166182, "3rd URL"=>166804, "4th URL"=>167351, "5th URL"=>165933}

我假设问题出在 Controller 中的“where”语句,我什至可能会不必要地多余第二行。

如有任何帮助,我们将不胜感激。

编辑:

这是日志生成的代码:

Started GET "/top_urls" for ::1 at 2015-02-16 11:46:06 -0700
Processing by PagestatsController#top_urls as HTML
[1m[35m (4077.3ms)[0m  SELECT  COUNT(*) AS count_all, url AS url FROM `urls` WHERE `urls`.`url` IN ('http://apple.com', 'https://apple.com', 'https://www.apple.com', 'http://developer.apple.com', 'http://en.wikipedia.org', 'http://opensource.org') GROUP BY url  ORDER BY `urls`.`created_at` ASC LIMIT 5
[1m[36mUrl Load (4600.9ms)[0m  [1mSELECT  `urls`.* FROM `urls` WHERE `urls`.`url` IN ('http://apple.com', 'https://apple.com', 'https://www.apple.com', 'http://developer.apple.com', 'http://en.wikipedia.org', 'http://opensource.org') GROUP BY url  ORDER BY `urls`.`created_at` ASC LIMIT 5[0m
Rendered pagestats/top_urls.html.erb within layouts/application (4608.1ms)
Completed 200 OK in 8735ms (Views: 42.0ms | ActiveRecord: 8687.0ms)

最佳答案

试试这个: @urls = Url.group('url').order('count(*) desc').limit(5).count

它将返回一个以 url 作为键、以 View 作为值的哈希值。

更新您的 View 代码:

<% @urls.each do |url, view_count| %>
<%= url %> Views: <%= view_count %>
<% end %>

关于mysql - 显示 mySQL 数据库中唯一记录的总数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28566558/

相关文章:

php - 在 Laravel 4 中使用 Eloquent 简单插入

ruby-on-rails - 如何获取has_many :through relation中的through实例

ruby - 无法重载运算符 +=

Ruby 异常处理 : can't suppress NoMethodError

mysql - 提高 SQL LIKE 查询性能

mysql - SQL 查询以显示包括产品图像在内的最新订单信息 (Prestashop)

php - 我的 PHP 生成的 CSV 文件保存为 PHP 文件

ruby-on-rails - 我在哪里可以只配置一次redis?

ruby-on-rails - 使用大于/小于搜索 Postgres JSON 类型

c++ - C++ 中 RUBY 的 GEMS 相当于什么?