Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql sql:DISTINCT给我重复的结果_Mysql_Ruby On Rails_Activerecord_Active Relation - Fatal编程技术网

Mysql sql:DISTINCT给我重复的结果

Mysql sql:DISTINCT给我重复的结果,mysql,ruby-on-rails,activerecord,active-relation,Mysql,Ruby On Rails,Activerecord,Active Relation,您好,我正在使用以下查询 Message.select("DISTINCT(commentable_id, user_id) as owner_id").map(&:owner_id) 它给了我这样的结果: [“(8,9)”、“(8,84)”、“(9,8)”、“(84,8)”] 这里“(8,9)”和“(9,8)”是不同的返回,但我只想要一条记录。方法 结果应该是这样的 [“(8,9)”,“(8,84)”] 那么我怎样才能实现它呢 更新 My table: id | user_id

您好,我正在使用以下查询

 Message.select("DISTINCT(commentable_id, user_id) as owner_id").map(&:owner_id)
它给了我这样的结果: [“(8,9)”、“(8,84)”、“(9,8)”、“(84,8)”]

这里“(8,9)”和“(9,8)”是不同的返回,但我只想要一条记录。方法 结果应该是这样的

[“(8,9)”,“(8,84)”] 那么我怎样才能实现它呢

更新

My table:

id | user_id | commentable_id
1  |  8      |      9
2  |  8      |      84
3  |  9      |      8
4  |  84     |      8
5  |  8      |     84
我想要id为1,2的结果。 实际上这是对话视图,所以我要么是发送者(用户id),要么是接收者(可评论id)。 如果我是id为8的用户,那么在对话视图中,我只有两个id为9和84的用户


感谢

SQL DISTINCT正在按其设计的方式工作。仅从SQL执行此操作可能太难了。由于您使用的是Ruby,我建议使用for-in循环或其他方法来进一步过滤结果。

您可以使用
grest()
least()函数在SQL中表达您想要的内容:

select distinct least(user_id, commentable_id) as id1, greatest(user_id, commentable_id) as id2
from mytable;

您也应该能够在Ruby on Rails中表达这一点。

您只是想要一个数组吗?