提交 87ca68e7 编写于 作者: R Ryuta Kamizono

Fix `COUNT(DISTINCT ...)` for `GROUP BY` with `ORDER BY` and `LIMIT`

This is the fix for the regression of #29848.

In #29848, I've kept existing select list in the subquery for the count
if ORDER BY is given. But it had accidentally affect to GROUP BY
queries also. It should keep the previous behavior in that case.

Fixes #30886.
上级 7089ee4e
* Fix `COUNT(DISTINCT ...)` for `GROUP BY` with `ORDER BY` and `LIMIT`.
Fixes #30886.
*Ryuta Kamizono*
## Rails 5.1.4 (September 07, 2017) ##
* No changes.
......
......@@ -195,7 +195,7 @@ def perform_calculation(operation, column_name)
if operation == "count"
column_name ||= select_for_count
if column_name == :all
if distinct && !(has_limit_or_offset? && order_values.any?)
if distinct && (group_values.any? || !(has_limit_or_offset? && order_values.any?))
column_name = primary_key
end
elsif column_name =~ /\s*DISTINCT[\s(]+/i
......
......@@ -265,6 +265,10 @@ def test_distinct_joins_count_with_order_and_limit_and_offset
assert_equal 3, Account.joins(:firm).distinct.order(:firm_id).limit(3).offset(2).count
end
def test_distinct_count_with_group_by_and_order_and_limit
assert_equal({ 6 => 2 }, Account.group(:firm_id).distinct.order("1 DESC").limit(1).count)
end
def test_should_group_by_summed_field_having_condition
c = Account.group(:firm_id).having("sum(credit_limit) > 50").sum(:credit_limit)
assert_nil c[1]
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册