我的数据库中有一个报告表。我正在执行一个复杂的查询,我想从结果中计算唯一的报告 ID。
我可以使用两种方法来做到这一点:
我在 mysql 查询中使用
DISTINCT
,例如select count(DISTINCT id) from reports where ...
我在执行原始 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/