简体   繁体   English

DB2 SQL-选择与另一个表相关的表的所有值

[英]DB2 SQL - Select all values of a table related to another table

Maybe I'm not clear on the topic for what I'm trying to ask, so here is my question: 也许我不清楚我要问的话题,所以这是我的问题:

I have three tables for now, say, User , User Role , Role , which make reference to each other: 我现在有三个表,分别是UserUser RoleRole ,它们相互引用:

User
========
USER_ID | USER_NAME 
1       | User A
2       | User B

User Role
========
USER_ID | ROLE_ID
1       | 1
1       | 2
2       | 1

Role
========
ROLE_ID | ROLE_NAME
1       | Admin
2       | Supervisor

As you can see, User A has two role for now: Admin and Supervisor What I'm trying to do now is selecting all users with role Admin , then the sql result should display all other roles related to that user also. 如您所见, User A目前具有两个角色: AdminSupervisor我现在想做的是选择所有具有Admin角色的用户,然后sql结果应显示与该用户相关的所有其他角色。

Say, the sql is executed like this: select A.*, C.ROLE_NAME from User A, User Role B, Role C where A.USER_ID = B.USER_ID and B.ROLE_ID = C.ROLE_ID and B.ROLE_ID = '1' 说,sql是这样执行的: select A.*, C.ROLE_NAME from User A, User Role B, Role C where A.USER_ID = B.USER_ID and B.ROLE_ID = C.ROLE_ID and B.ROLE_ID = '1'

The above sql should only display User A with only one role, Admin : 上面的sql应该只显示只有一个角色Admin User A

USER_ID | USER_NAME | ROLE_NAME
1       | User A    | Admin
2       | User B    | Admin

But what I want is, beside Admin , the sql result should also display User A with ROLE_NAME = Supervisor : 但是我想要的是,在Admin旁边,sql结果还应该显示具有ROLE_NAME = Supervisor User A

USER_ID | USER_NAME | ROLE_NAME
1       | User A    | Admin
1       | User A    | Supervisor
2       | User B    | Admin

Any ideas? 有任何想法吗?

Use exists : exists用途:

with ur as (
      select u.*, C.ROLE_NAME
      from User u join
           User_Role ur
           on u.user_id = ur.user_id join
           Role r 
           on r.role_id = ur.role_id
     )
select ur.*
from ur
where exists (select 1
              from ur ur2
              where ur2.user_id = ur.user_id and ur2.role_name = 'admin'
             );

Also, never use commas in the FROM clause. 另外, 切勿FROM子句中使用逗号。 Always use proper, explicit JOIN syntax with the condition in the ON clause. 始终ON子句中的条件使用正确的显式JOIN语法。

Second, use meaningful table aliases rather than arbitrary letters such as "a", "b", and "c". 其次,使用有意义的表别名,而不要使用诸如“ a”,“ b”和“ c”之类的任意字母。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM