当第二个表中布尔值为TRUE时,用第一个表覆盖第二个表的结果

时间:2017-02-13 15:59:59

标签: sql postgresql

       role_cap                                    enduser_cap
       _____________________________________      _____________
       role_id  user_cap_id  is_present           id  user_cap_id is_granted
       -------------------------------------      -------------------------
       8        29            false               17    50         true
       7        32            true                21    30         true
       8        30            false               66    20         false
       8        13            true                21    29         true
       8        11            false

我希望所有user_cap_id role_caprole_id = 8is_present is_grantedenduser_cap覆盖id = 21 _________________________ user_cap_id ------------------------- 29 30 13 select * from role_cap where role_id = 8 select * from enduser_cap where id = 21 }}

结果应该变成:

Date

我可以通过以下单个查询来获取它:

java-1.6

第二个查询的结果应合并到第一个查询中,以便: “当第二个表中布尔值为TRUE时,覆盖第二个表与第一个表的结果”

在role_cap和enduser_cap表中,什么是TRUE应该成为结果的一部分。但是,如果role_cap具有FALSE条目且enduser_cap具有相同user_cap_id的TRUE条目,则enduser_cap的TRUE将作为优先级给出。

2 个答案:

答案 0 :(得分:1)

在检查用户在enduser_cap表中是否为true且id = 21或在role_cap本身中为true时,听起来像OR操作。

select user_cap_id
from role_cap r
where role_id = 8
    and (
        exists (
            select 1
            from enduser_cap u
            where u.user_cap_id = r.user_cap_id
                and id = 21
                and is_granted
            )
        or is_present
        );

Demo

答案 1 :(得分:0)

如果您想查看被enduser_cap记录(id = 21)覆盖的role_cap(具有role_id = 8)的记录,请使用:

SELECT r.user_cap_id 
FROM role_cap r, enduser_cap e
WHERE r.role_id = 8 AND e.id=21 AND 
      r.user_cap_id=e.user_cap_id AND r.is_present <> e.is_granted

你应该得到:

user_cap_id
------------
29
30