当我想要的实际值是第二个表到第三个表的引用时,我如何在两个表之间用左连接(Oracle)构造SQL?

ha5z0ras  于 2023-08-03  发布在  Oracle
关注(0)|答案(1)|浏览(75)

我很难用搜索的方式描述这个问题(谷歌):
我正在创建一个基于多个表的或多或少的左联接的视图。原始表(左)中充满了外键,我需要用值替换这些外键。我使用Left连接引用的表来实现这一点。然而,这些左连接表中的一些只给予我另一个外键,然后我需要子查询以获得我想要的值。我敢打赌有一个简单的答案,但我的googlefu是不值得的。
示例如下:
Table details
从视图SQL中提取(已批量删除)

CREATE OR REPLACE VIEW VW_EQ_HISTORY (
id,
tag,
original_wo,
wo_status,
wo_task_code,
wo_task_name,
(etc)...
)
AS
SELECT
a.wmm_eqhist_id id,
b.wmt_tag_name tag,
c.wmm_wo_code original_wo,
c.elc_status_id wo_status,
d.wmm_wotask_id wo_taske_code,
d.wmm_wotask_id wo_task_name,
(etc)...

FROM WMM_EQUIPHISTORY a
LEFT JOIN wmt_tag b ON (a.wmt_tag_id = b.wmt_tag_id)
LEFT JOIN wmm_workorder c ON (a.wmm_wo_id = c.wmm_wo_id)
LEFT JOIN wmm_woitem d ON (a.wmm_woitem_id = d.wmm_woitem_id)
(etc)...
WHERE a.wmm_eqhist_createddate >= To_Date ('01/JAN/2013','dd/mon/yyyy') 
WITH READ ONLY
 CONSTRAINT vw_eq_history
/

GRANT SELECT ON vw_eq_history TO pbiuser;

字符串
wo_status列从wmm_workorder获取elc_status_id,但我希望elc_statuses表中的名称/描述替换视图中的elc_status_id。
我尝试子查询'(Select...)as wo_status',但不得不给予...

5vf7fwbs

5vf7fwbs1#

假设从wmm_workorderelc_statuses存在 * 对1的相关性,则将其作为JOIN包含在内:

CREATE OR REPLACE VIEW VW_EQ_HISTORY (
  id,
  tag,
  original_wo,
  wo_status,
  wo_task_code,
  wo_task_name,
  (etc)...
)
AS
SELECT a.wmm_eqhist_id,
       b.wmt_tag_name,
       c.wmm_wo_code,
       s.name_or_description,
       d.wmm_wotask_id,
       d.wmm_wotask_id,
       (etc)...
FROM   WMM_EQUIPHISTORY a
       LEFT JOIN wmt_tag b ON (a.wmt_tag_id = b.wmt_tag_id)
       LEFT JOIN wmm_workorder c ON (a.wmm_wo_id = c.wmm_wo_id)
       LEFT JOIN elc_statuses s ON (c.elc_status_id = s.elc_status_id)
       LEFT JOIN wmm_woitem d ON (a.wmm_woitem_id = d.wmm_woitem_id)
       (etc)...
WHERE  a.wmm_eqhist_createddate >= DATE '2023-01-01'
WITH READ ONLY
 CONSTRAINT vw_eq_history
/

字符串
或者,将其指定为INNER JOIN并使用括号设置JOIN s的优先级:

CREATE OR REPLACE VIEW VW_EQ_HISTORY (
  id,
  tag,
  original_wo,
  wo_status,
  wo_task_code,
  wo_task_name,
  (etc)...
)
AS
SELECT a.wmm_eqhist_id,
       b.wmt_tag_name,
       c.wmm_wo_code,
       s.name_or_description,
       d.wmm_wotask_id,
       d.wmm_wotask_id,
       (etc)...
FROM   WMM_EQUIPHISTORY a
       LEFT JOIN wmt_tag b ON (a.wmt_tag_id = b.wmt_tag_id)
       LEFT JOIN (
         wmm_workorder c
         INNER JOIN elc_statuses s ON (c.elc_status_id = s.elc_status_id)
       ) ON (a.wmm_wo_id = c.wmm_wo_id)
       LEFT JOIN wmm_woitem d ON (a.wmm_woitem_id = d.wmm_woitem_id)
       (etc)...
WHERE  a.wmm_eqhist_createddate >= DATE '2023-01-01'
WITH READ ONLY
 CONSTRAINT vw_eq_history
/

相关问题