简体   繁体   English

具有不同列的随机顺序

[英]Random order with distinct column

I am creating a query which involves several joins, which causes some duplicates 我正在创建一个涉及多个联接的查询,这会导致一些重复

@users = User.joins(...).where(...).select("users.id")

From that result I want to make the records distinct and in RANDOM() order 从该结果中,我想使记录distinct并按RANDOM()顺序排列

I can't seem to recreate that with activerecord. 我似乎无法用activerecord重新创建它。

With SQL it would look something like 使用SQL,它看起来像

SELECT DISTINCT users.*
from ( long complex query)
ORDER BY RANDOM()

One of the easiest things to do, rather than building complex queries in any framework, is to build the complex query with standard SQL and then wrap it in a view: 与在任何框架中构建复杂查询相比,最简单的操作之一是使用标准SQL构建复杂查询,然后将其包装在视图中:

CREATE VIEW complex_stuff AS
  SELECT DISTINCT users.*
  FROM ( long complex query)
  ORDER BY RANDOM();

The view becomes a simple entity or class from which you pull the required columns, possibly filtering by some column ( SELECT a, b, c FROM complex_stuff WHERE d = ? ). 视图变成一个简单的实体或类,您可以从中提取所需的列,并可能按某些列进行过滤( SELECT a, b, c FROM complex_stuff WHERE d = ? )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM