简体   繁体   中英

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

I can't seem to recreate that with activerecord.

With SQL it would look something like

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:

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 = ? ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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