给出两个查询:
@users1 = Users.find_by_company_id(2)
@users2 = Users.find_by_office_id(2)
我想把两者结合起来:
@users_to_show = @users1 + @users2
问题是如何防止重复用户显示。有没有办法将两者结合起来(数组?)然后确保删除重复的记录?
由于
更新:
# This QUERY gives all of a user's project members, people they work with
@project_ids = @projects.map(&:project_id)
@users = User.find_by_sql [
"SELECT DISTINCT users.*
FROM users
INNER JOIN permissions ON permissions.user_id = users.id
WHERE project_id IN (?) AND permissions.user_id != ?
UNION ALL
SELECT DISTINCT users.*
FROM users
WHERE instance_id = ?",
@project_ids, current_user.id, current_user.instance_id
]
答案 0 :(得分:2)
这是一种可能适合您的手动SQL方法:
@users = User.find_by_sql("
SELECT DISTINCT * FROM USERS WHERE [Place your First complicated where clauses Here]
UNION
SELECT * FROM USERS WHERE instance_id = ?
", current_user.instance_id)
修改强>: UNION将在两个查询之间对重复记录进行精简。
编辑:确保每个查询都不会独立生成重复项。 Union不会删除单个查询中的重复项。