如果在另一个表中引用行id,如何显示为列?

时间:2014-07-10 16:07:26

标签: sql oracle join

有两张桌子:

[TableRule]
|RuleId (PK)|
|RuleDesc|
...

[TableRulesByUser]
|UserId|
...
|RuleId (FK)|

我希望使用额外的列检索所有TableRules,该列显示是否使用(引用)此RuleId。

我尝试过类似的事情:

select v.*,
            case
                when
                    (select count(b.RuleId) from TableRulesByUser b
                    join v on b.RuleId = v.RuleId  ) > 1
                    /* Here the join doesn't work */
                then 'Y' IsUsed
                else 'N' IsUsed
            end
    from TableRule v

2 个答案:

答案 0 :(得分:0)

尝试类似:

select 
v.*,
case when b.RuleId > 1
then 'y' 
else 'n' 
end
from tablerulesbyuser b
join tablerule v
on b.ruleid = v.ruleid
Group BY RuleDesc

答案 1 :(得分:0)

SELECT
V.*,
CASE WHEN U.RuleID IS NULL THEN 'N' ELSE 'Y' END
FROM TABLERULES V
LEFT JOIN TABLERULESBYUSER U ON V.RuleID = U.RuleID

不确定PLSQL的语法是否正确,但想法是LEFT JOIN另一个表,如果没有使用,你将获得null,然后显示N,否则为Y.