mysql DISTINCT 和 Rails uniq 查找唯一记录

标签 mysql ruby-on-rails

我的数据库中有一个报告表。我正在执行一个复杂的查询,我想从结果中计算唯一的报告 ID。

我可以使用两种方法来做到这一点:

  1. 我在 mysql 查询中使用 DISTINCT,例如 select count(DISTINCT id) from reports where ...

  2. 我在执行原始 SQL 查询的结果上使用 Rails uniq 方法。

但这两个数字不同。

此外,当我将 LIMIT(n) 与 DISTINCT 查询 (#1) 结合使用时,这两个计数都匹配。我不知道为什么会发生这种情况!我的表中该列没有 NULL 值。

这是 mysql 查询:

select count(distinct report_id)
  from table1 cas
 where not exists (select 1
                     from table2 t
                    where t.report_id = cas.report_id
                      and t.point_id = cas.point_id);

Rails 查询:

ActiveRecord::Base.connection.execute("select report_id
  from table1 cas
 where not exists (select 1
                     from table2 t
                    where t.report_id = cas.report_id
                      and t.point_id = cas.point_id);").to_a.flatten.uniq.count

最佳答案

既然你已经使用了原始sql,你不妨用它来完成整个任务

ActiveRecord::Base.connection.execute("select count (distinct report_id) 
  from table1 cas
 where not exists (select 1
                     from table2 t
                    where t.report_id = cas.report_id
                      and t.point_id = cas.point_id);").first.count

关于mysql DISTINCT 和 Rails uniq 查找唯一记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36976655/

相关文章:

ruby-on-rails - Rails 模型的 XML 映射和验证

ruby-on-rails - rails : Different behavior on dev and production

Mysql - 索引性能

MySQL Where 子句 - 获取两个城市,其中 1. 行的 ID < 2. 行的 ID

MySQL JOIN 语句按选定的链接属性过滤行

ruby-on-rails - 如何以不同方式对字符串列进行排序

ruby-on-rails - 使用载波上传到 S3 时获取 mp3 持续时间

mysql日期范围忽略结果中的结束日期

php - 如果 4 个 mysql 查询中的任何一个失败,如何设置 mysqli 错误

ruby-on-rails - MongoDB - Mongoid map reduce基本操作