我正在研究一个项目,我需要解决这个问题。 非常感谢所有可以帮助我的人。
我有2张桌子
ARTICLE(id,artNum,artType)
REQUIREDENGINEERS(id,artNum,artType,reqEngineer)
(artNum,artType)
的所有情侣REQUIREDENGINEERS
都在ARTICLE
但不是相反。
我将ARTICLE ID
作为参数,我需要检索reqEngineer
。
问题是当我在(artNum,artType)
中没有亲戚REQUIREDENGINEERS
时,我应该只使用artType并使用max(reqEngineer)
。
我试过但我无法弄明白。显然我的解决方案是错误的,但也许可以保存一些东西
select (case
when t_art.ARTNUM is null then (select max(g.REQENGINEERS)
from REQUIREDENGINEERS g
where g.ARTTYPE= t_dur.ARTTYPE)
else t_dur.REQENGINEER
end) as required_engineers
FROM
ARTICLE t_art,
REQUIREDENGINEERS t_dur
WHERE
:id = t_art.ID AND
t_art.ARTNUM = t_dur.ARTNUM AND
t_art.ARTTYPE = t_dur.ARTTYPE;
答案 0 :(得分:1)
这可能不是表现最佳的解决方案,但可以作为起点。
这里是样本数据
create table ARTICLE as
select 1 id, 1 artNum, 1 artType from dual union all
select 2 id, 2 artNum, 2 artType from dual;
create table REQUIREDENGINEERS as
select 1 id, 1 artNum, 1 artType, 1 reqEngineer from dual union all
select 2 id, 1 artNum, 1 artType, 2 reqEngineer from dual union all
select 3 id, 1 artNum, 2 artType, 1 reqEngineer from dual union all
select 4 id, 1 artNum, 2 artType, 2 reqEngineer from dual;
WHERE
条件中的查询与您的要求相同。
选择所有匹配(artNum, artType)
或不匹配EXISTS
使用artType
但约束max(reqEngineer)
with art as (select artNum, artType from ARTICLE where id = :id)
select * from REQUIREDENGINEERS r
where (artNum, artType) in (select artNum, artType from art) or
not exists (select null from REQUIREDENGINEERS where (artNum, artType)
in (select artNum, artType from art)) and
artType in (select artType from art) and reqEngineer =
(select max(reqEngineer) from REQUIREDENGINEERS where artType = r.artType);
这里结果为1 - 两个属性都直接匹配
ID ARTNUM ARTTYPE REQENGINEER
---------- ---------- ---------- -----------
1 1 1 1
2 1 1 2
和2 - 在artNum上匹配,只选择(全部)最大REQENGINEER
ID ARTNUM ARTTYPE REQENGINEER
---------- ---------- ---------- -----------
4 1 2 2
答案 1 :(得分:0)
可能有几种方法可以解决这个问题,但最简单的方法可能是使用两个单独的查询(一个用于两个字段都匹配,另一个用于不存在的情况)和关于结果的联盟。这可能有用:
SELECT T_DUR.REQENGINEERS
FROM ARTICLE T_ART
JOIN REQUIREDENGINEERS T_DUR ON T_ART.ID = T_DUR.ID
AND T_ART.ARTNUM = T_DUR.ARTNUM
AND T_ART.ARTTYPE = T_DUR.ARTTYPE
UNION ALL
SELECT MAX(T_DUR.REQENGINEERS)
FROM ARTICLE T_ART
JOIN REQUIREDENGINEERS T_DUR ON T.ART.ID = T_DUR.ID
AND T_ART.ARTTYPE = T_DUR.ARTTYPE
WHERE T_ART.ARTTYPE NOT IN (SELECT T_ART.ART_TYPE
FROM ARTICLE T_ART
JOIN REQUIREDENGINEERS T_DUR ON T_ART.ID = T_DUR.ID
AND T_ART.ARTNUM = T_DUR.ARTNUM
AND T_ART.ARTTYPE = T_DUR.ARTTYPE