2016-05-02 19 views
0

我在我的數據庫中有一個報告表。我正在執行一個複雜的查詢,我想從結果中計算唯一的報告ID。mysql DISTINCT和Rails uniq找到唯一記錄

我能做到這一點使用2種方式:

  1. 我在MySQL查詢使用DISTINCTselect count(DISTINCT id) from reports where ...

  2. 我使用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 
+0

'我對執行原始sql查詢的結果使用Rails uniq方法。'您的原始查詢是否僅包含'id'或其他列? – lad2025

+0

你可以通過示例sqls來闡述這個問題嗎? –

+0

添加了mysql查詢。 –

回答

0

既然你已經使用原始的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