0

I have a complex query like this:

SELECT count(*)
FROM users a 
WHERE source = 1 
  AND ... -- COMPLEX QUERY
  AND NOT EXISTS (
    SELECT 1 FROM users b
    WHERE b.source = 0
      AND ... -- COMPLEX QUERY
      AND b.key = a.key
);

The COMPLEX QUERY is generated in:

Rails:
@scope = User.complex_scope(params)

How do I build above query by Activerecord in rails?

Thank you!

  • 2
    Could you please explain why you think your query is complex? Is it only for using nested sub-queries? In that case you can check [here](https://stackoverflow.com/questions/5483407/subqueries-in-activerecord) – mehedi Dec 19 '18 at 10:25
  • Thank @mehedi for your care! I mean it's complex because in the subquery I need to use the same table with the parent query. In SQL we can use an alias name like **FROM users a** and **From users b** to indent subquery with the parent query. In your example, the subquery and parent query are in different table SELECT * FROM users WHERE id IN (SELECT user_id FROM accounts WHERE ..). – Thịnh Nguyễn Thái Dec 20 '18 at 03:56

0 Answers0