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

时间:2015-02-17 16:47:20

标签: mysql ruby-on-rails ruby

我正在尝试完成一项任务,我在mySQL数据库中有100万条记录,每条记录都有一个URL和一个引用URL(当然还有一个ID)。作业的部分目标是通过“视图”显示前5个出现的URL(AKA:每个URL在数据库中的记录频率)

我相信我非常接近,因为我现在有前5个网址显示,但我的问题是我只能获得要显示的记录总数(1000000或每个连续网址的视图互相跟随)在同一行)

我的控制器代码如下所示: (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

我的观看代码如下所示:

<% @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}

我假设问题出在控制器中的“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)

1 个答案:

答案 0 :(得分:0)

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

它将返回一个哈希,其中url为键,视图为值。

更新您的观看代码:

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