使用Active Record,Rails&查找具有多个重复字段的行Postgres

编程入门 行业动态 更新时间:2024-10-26 06:32:53
本文介绍了使用Active Record,Rails&查找具有多个重复字段的行Postgres的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

使用Postgres和Activerecord在多个列中查找具有重复值的记录的最佳方法是什么?

What is the best way to find records with duplicate values across multiple columns using Postgres, and Activerecord?

我找到了此解决方案此处:

User.find(:all,:group => ; [:first,:email],:having => count(*)> 1)

但是它没有似乎可以和postgres一起使用。我收到此错误:

But it doesn't seem to work with postgres. I'm getting this error:

PG :: GroupingError:错误: parts.id列必须出现在GROUP BY子句中或在聚合函数中使用

PG::GroupingError: ERROR: column "parts.id" must appear in the GROUP BY clause or be used in an aggregate function

推荐答案

经过测试的&工作版本

User.select(:first,:email).group(:first,:email).having("count(*) > 1")

此外,这有点无关,但方便。如果要查看每个组合的查找时间,请在末尾加上.size:

Also, this is a little unrelated but handy. If you want to see how times each combination was found, put .size at the end:

User.select(:first,:email).group(:first,:email).having("count(*) > 1").size

,您将获得如下所示的结果集:

and you'll get a result set back that looks like this:

{[nil, nil]=>512, ["Joe", "test@test"]=>23, ["Jim", "email2@gmail"]=>36, ["John", "email3@gmail"]=>21}

认为这很酷,以前从未见过。

Thought that was pretty cool and hadn't seen it before.

感谢Taryn,这只是她答案的调整版本。

Credit to Taryn, this is just a tweaked version of her answer.

更多推荐

使用Active Record,Rails&查找具有多个重复字段的行Postgres

本文发布于:2023-10-16 10:39:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1497332.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   字段   Record   Active   Rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!