如何查找查询结果的大小 [英] How to find size of query result
问题描述
records = Record.select('y_id,source')
.where(:source => source,:y_id => y_id)
.group(:y_id,:source)
.having('count(*)= 1')
如果我 puts记录
,我会得到以下输出:<
[#<记录来源:XYZ,y_id:10000009> ;,#<记录来源:XYZ,y_id:10000070>]
这看起来像输出数组中有2个元素。但是当我尝试做 records.size
时,我得到:
{[10000009,XYZ] => 1 ,[10000070,XYZ] => 1}
- b
当记录是一个有2个元素的数组时,为什么不是
records.size
print2
由于某种原因,组由
查询结果的行为有所不同?
$ b
我可能走错了路,但我认为问题在于以
尺寸会自动尝试确定是否调用 .count
或 .length
。它们的行为如下所示:
- .count执行SQL COUNT
- .length计算结果数组的长度
然而,在事件 .size
中将返回一个散列(因为它已经决定使用 .count
)
所以你的解决方案可能是使用 .length
,它将返回一个整数。
I have the following query in rails:
records = Record.select('y_id, source')
.where(:source => source, :y_id => y_id)
.group(:y_id, :source)
.having('count(*) = 1')
I get the following output if I puts records
:
[#<Record source: "XYZ", y_id: 10000009>, #<Record source: "XYZ", y_id: 10000070>]
This looks like there are 2 elements in the output array. But when I try to do records.size
I get:
{[10000009, "XYZ"]=>1, [10000070, "XYZ"]=>1}
Why doesn't
records.size
print2
when records is an array having 2 elements? Is thegroup by
query result behaving differently for some reason?What should I do to get the size of
records
I could be on the wrong track but I think the issue is to do with the way .size
works.
Size will automatically try to determine whether to call .count
or .length
. These behave in the followings ways:
- .count performs a SQL COUNT
- .length calculates the length of the resultant array
However on occassion .size
will return a hash (as it has decided to use .count
)
So your solution may be to use .length
which will return an integer.
这篇关于如何查找查询结果的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!