说我有单个db2表 FACT_VEHICLE ,包含以下行:
FACT_VEHICLE
___________________________________________________________
**ID** |**COLOR** |**ADDITIONAL_INFO**
___________________________________________________________
1 |BLUE |
___________________________________________________________
2 |RED |1
从这张表中,我创建了一个看起来像这样的视图:
VIEW_VEHICLE
____________________________________________________________
**ID** |**COLOR_1** |**COLOR_2**
____________________________________________________________
1 |BLUE |
____________________________________________________________
2 |RED |BLUE
要在视图中显示 COLOR_2 行的内容,我已经考虑过这样做一个子选择:
SELECT
f.ID AS ID,
f.COLOR AS COLOR_1,
f2.COLOR AS COLOR_2
FROM FACT_VEHICLE f JOIN FACT_VEHICLE f2 ON f2.ID = f.ADDITIONAL_INFO;
这是最有效的方法吗?
答案 0 :(得分:0)
你有null或值不存在的问题(例如,如果你有一个fk之间 同一个表上的ADDITIONAL_INFO和ID,当然是null启用)
SELECT f1.ID AS ID, f2.COLOR AS COLOR_1, ifnull(f2.COLOR, '') AS COLOR_2
FROM FACT_VEHICLE f1
LEFT OUTER JOIN FACT_VEHICLE f2 ON f2.ID = f1.ADDITIONAL_INFO;