左外sql连接问题

时间:2014-11-05 16:31:19

标签: sql ruby-on-rails postgresql

我想显示所有没有隐藏的可见性规则的产品:true。我无法弄清楚sql。我有以下4个表:

products:
id: integer
name: string

role:
id: integer
name: string

user_roles:
user_id: integer
role_id: integer

visibility_rules:
hidden: boolean
product: integer
role: text

我尝试了以下

SELECT spree_products.* 
FROM spree_products 
LEFT OUTER JOIN spree_visibility_rules ON spree_visibility_rules.product_id
                                        = spree_products.id 
  AND spree_visibility_rules.role_name IN ('Student','Admin') 
  WHERE spree_products.deleted_at IS NULL 
    AND (spree_visibility_rules.visible IS NULL)

如果我有多个角色(学生和管理员等),那么我想查找至少一个用户角色可见的所有产品。上述sql的问题在于,只有产品对所有用户角色都可见时,它才会起作用。如果它隐藏到Student角色,那么即使它对Admin角色可见,它也不会返回产品。我想我误解了Left outer join。

3 个答案:

答案 0 :(得分:0)

你需要一个子选择。

SELECT
  *
FROM
  spree_products
WHERE
  id IN (
    SELECT
      product_id
    FROM
      spree_visibility_rules
    WHERE
      NOT hidden
  );

答案 1 :(得分:0)

select sp.id,sp.name,svr.hidden from spree_products sp
inner join spree_visibility_rules svr
on sp.id = svr.product
where svr.hidden = 0

答案 2 :(得分:0)

给定 user_id的可见产品:

SELECT p.*
FROM   user_roles       ur
JOIN   role             r  ON r.id = ur.role_id
JOIN   visibility_rules vr ON vr.role = r.id
JOIN   spree_products   p  ON p.id = vr.product
WHERE  ur.user_id = 123   -- given user_id
AND    NOT vr.hidden
GROUP  BY p.id;           -- must be defined as PK

根据细节,可能会进一步优化性能。