0
我在我的數據庫中有一個報告表。我正在執行一個複雜的查詢,我想從結果中計算唯一的報告ID。mysql DISTINCT和Rails uniq找到唯一記錄
我能做到這一點使用2種方式:
我在MySQL查詢使用
DISTINCT
像select count(DISTINCT id) from reports where ...
我使用Rails的uniq的方法上執行的原始SQL查詢的結果。
但這兩個數字都不相同。
另外,當我使用LIMIT(n) with DISTINCT query (#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查詢的結果使用Rails uniq方法。'您的原始查詢是否僅包含'id'或其他列? – lad2025
你可以通過示例sqls來闡述這個問題嗎? –
添加了mysql查詢。 –