DB2 SQL:更改连接查询以提供所需的结果

时间:2015-04-03 21:08:09

标签: sql db2

主要Table_1

ID    ROLE              CODE
______________________________
1     DIRECTOR          CD1
1     PRODUCER          CD2 
1     ACTOR             CD10
2     PRODUCER          CD5
2     ACTOR             CD11
2     DIRECTOR          CD8
2     SPOT_BOY          CD97
3     ACTOR             CD12
3     DIRECTOR          CD41
______________________________

参考Table_2

COL_NAME     REF_VALUE
____________________________
DIRECTOR     DIR
PRODUCER     PROD
ACTOR        ACT
SPOT_BOY     SPB
____________________________
ROLE的{​​p> Table_1列与COL_NAME的{​​{1}}列加入

参考Table_2

Table_3
CODE NAME _________________________ CD1 ONE CD2 TWO CD5 FIVE CD10 TEN CD11 ELEVEN CD12 TWELVE CD97 NINETY_SEVEN CD8 EIGHT CD41 FORTY_ONE _________________________ 的{​​p> CODE列与Table_1的{​​{1}}列加入

查询:

CODE

结果:

Table_3

如果不修改三个表中的任何一个,我想修改上面的查询,以便:select a.id, a.role, b.ref_value, c.code, c.name from table_1 a, table_2 b, table_3 c where a.id = 1 and a.role = b.col_name and a.code = c.code ID ROLE REF_VALUE CODE NAME ___________________________________________ 1 DIRECTOR DIR CD1 ONE 1 PRODUCER PROD CD2 TWO 1 ACTOR ACT CD10 TEN ___________________________________________ ROLE Table_1PRODUCER REF_VALUE 1}}是Table_2),来自PROD的相应CODE(或来自Table_1的{​​{1}})和来自CODE的{​​{1}}应该被视为Table_3 NAME的{​​{1}} Table_3

即。 ROLE 1的修改后的查询应该导致:

DIRECTOR

ID 2的修改后的查询应该会产生:

ID

换句话说,使用上面给出的表结构(并且没有修改表中结构或数据的选项),我想要一个查询,其中给出任何ID ROLE REF_VALUE CODE NAME ___________________________________________ 1 DIRECTOR DIR CD1 ONE 1 PRODUCER PROD CD1 ONE 1 ACTOR ACT CD10 TEN ___________________________________________ ID和{{ 1}}角色ID ROLE REF_VALUE CODE NAME _____________________________________________________ 2 PRODUCER PROD CD8 EIGHT 2 ACTOR ACT CD11 ELEVEN 2 DIRECTOR DIR CD8 EIGHT 2 SPOT_BOY SPB CD97 NINETY_SEVEN _____________________________________________________ ID的值应该是与CODE的角色NAME对应的值。

我正在使用DB2数据库。

感谢阅读!

1 个答案:

答案 0 :(得分:0)

通过额外的连接,这非常简单。不过,最简单的方法是将它包装在子查询或CTE中:

WITH PrdDir AS (SELECT Df.id, Df.role, COALESCE(Ot.code, Df.code) AS code
                FROM Table_1 Df
                LEFT JOIN Table_1 Ot
                       ON Ot. id = Df.id
                          AND Df.role = 'PRODUCER'
                          AND Ot.role = 'DIRECTOR')

SELECT PrdDir.id, PrdDir.role, Table_2.ref_value, Table_3.code, Table_3.name 
FROM PrdDir
JOIN Table_2
  ON Table_2.col_name = PrdDir.role
JOIN Table_3
  ON Table_3.code = PrdDir.code

SQL Fiddle Example

请不要使用隐式连接语法(逗号分隔的FROM子句) - 首先,你不能在DB2中用它来LEFT JOIN - 在这个查询中,如果没有导演,至少生产者仍然会被退回。另一方面,很容易忘记一个条件,偶然得到笛卡尔积。