Intersection of two relations

前端 未结 5 2083
情歌与酒
情歌与酒 2020-12-16 17:06

Say I have two relations that hold records in the same model, such as:

@companies1 = Company.where(...)
@companies2 = Company.where(...)

Ho

5条回答
  •  轮回少年
    2020-12-16 17:22

    Use sql keyword INTERSECT.

    params1 = [1,2,4]
    params2 = [1,3,4]
    query = "
    SELECT companies.* FROM companies
    WHERE id in (?,?,?)
    INTERSECT
    SELECT companies.* FROM companies
    WHERE id in (?,?,?)
    "
    Company.find_by_sql([query, *params1, *params2])
    

    it will be faster than previous solution.

提交回复
热议问题