我正在尝试使用ActiveRecord编写一个简单的EXISTS查询。由于某种原因,它似乎正在运行2个查询。
User.where("exists (select 'X' from roles where roles.role = 'teacher' and roles.user_id = users.id)")
从日志中
查询1
(1.2ms) SELECT COUNT(count_column) FROM (SELECT 1 AS count_column FROM "users" WHERE (users.id <> 3 and exists (select 'X' from roles where roles.role = 'teacher' and roles.user_id = users.id)) LIMIT $1 OFFSET $2) subquery_for_count [["LIMIT", 2], ["OFFSET", 0]]
查询2
User Load (1.0ms) SELECT "users".* FROM "users" WHERE (users.id <> 3 and exists (select 'X' from roles where roles.role = 'teacher' and roles.user_id = users.id)) LIMIT $1 OFFSET $2 [["LIMIT", 2], ["OFFSET", 0]]
有没有办法避免这种情况。我会直接在SQL中编写查询,如下所示:
SELECT u.*
FROM users u,
roles r
WHERE r.user_id = u.id
AND u.id <> #{@user.id}
AND r.role = 'teacher'