我正在尝试优化Active Record中查询的性能。以前,我会执行两个SQL查询,并且应该可以一次执行。
这些是我正在其中运行查询的表:
# Table name: notifications
#
# id :integer not null, primary key
# content :text(65535)
# position :integer
# Table name: dismissed_notifications
#
# id :integer not null, primary key
# notification_id :integer
# user_id :integer
这是现有查询:
where.not(id: user.dismissed_notifications.pluck(:id))
产生:
SELECT `dismissed_notifications`.`id` FROM `dismissed_notifications` WHERE `dismissed_notifications`.`user_id` = 655
SELECT `notifications`.* FROM `notifications` WHERE (`notifications`.`id` != 1)
这是我想获取的SQL,它返回相同的记录:
select *
from notifications n
where not exists(
select 1
from dismissed_notifications dn
where dn.id = n.id
and dn.user_id = 655)
答案 0 :(得分:5)
您可以像下面这样编写not exists
查询
where('NOT EXISTS (' + user.dismissed_notifications.where('dismissed_notifications.id = notifications.id').to_sql + ')')
OR
还有另一种减少查询数量的方法是使用select
代替pluck
,它将创建子查询而不是从数据库中提取记录。 Rails ActiveRecord Subqueries
where.not(id: user.dismissed_notifications.select(:id))
这将在下面生成SQL查询
SELECT `notifications`.*
FROM `notifications`
WHERE (
`notifications`.`id` NOT IN
(SELECT `dismissed_notifications`.`id`
FROM `dismissed_notifications`
WHERE `dismissed_notifications`.`user_id` = 655
)
)