在case表达式中使用select子句来设置条件

xvw2m8pv  于 2021-08-13  发布在  Java
关注(0)|答案(5)|浏览(354)

查询1

select * from worklog where worklog.recordkey IN
       case 
       when worklog.class ='ACTIVITY'  THEN (SELECT wonum from woactivity where parent ='M2176' )
       when worklog.class ='WORKORDER' THEN  (SELECT WONUM FROM WORKORDER WHERE WONUM = 'M2176')
       end ;

问题2:

SELECT * from worklog
       WHERE CASE WHEN worklog.class='ACTIVITY' THEN 
                       worklog.recordkey in (select wonum from woactivity where parent='M2176' ) 
             end
                  WHEN worklog.class='WORKORDER' THEN 
                       worklog.recordkey = (select wonum from workorder where wonum='M2176')  
             end  ;

在上面的查询中,我需要在worklog.recordkey中设置一个值。当worklog.class为“activity”时,我有两个条件,必须从woactivity wonum设置vat值,如果worklog.class为“workorder”,则必须从workorder表设置值。当我使用上述查询时,会出现如下错误:
“”中关键字“附近的语法不正确”

“关键字”“case”“附近的语法不正确。”。
请帮帮我。

nzkunb0c

nzkunb0c1#

因为 workorder 是一张table woactivity 基本上就是那张table上的一个视图 where woclass = 'ACTIVITY' ,您可以通过以下方式简化查询:

select * from worklog where
(class, recordkey, siteid) in (select woclass, wonum, siteid from workorder)
and wonum='M2176'

如果上面的内容在sql server上不适用,请根据@dex的评论,将其翻过来:

select * From worklog where
exists (select 1 from workorder wo where 
    wo.woclass = worklog.class
    and wo.siteid = worklog.siteid
    and wo.wonum = worklog.wonum)
and wonum='M2176'

注意,我添加了 siteid 加入比较组合,因为 workorder 是站点级别的信息。

xriantvc

xriantvc2#

跳过 case 表达式,使用正则表达式 AND / OR 取而代之的是:

SELECT * from worklog
WHERE (worklog.class = 'ACTIVITY' and
       worklog.recordkey in (select wonum from woactivity where parent='M2176')) 
   OR (worklog.class='WORKORDER' AND 
       worklog.recordkey = (select wonum from workorder where wonum='M2176'))
o2g1uqev

o2g1uqev3#

如上所述:
1) workorder是一个基表,woactivity将根据workorder.woclass属性限制此表的视图
2) workorder对象的逻辑键是siteid+wonum。i、 在整个环境中,wonum值可能不是唯一的。
3) 与特定工单相关的所有记录将具有相同的sited+wogroup值。
4) 主工单记录的istask=0和wonum=wogroup,而关联的活动的istask=1。

blmhpbnm

blmhpbnm4#

你不需要使用 CASE . 我想你可以用布尔运算符来完成你想做的事情

查询1

select * from worklog where 
  (worklog.class ='ACTIVITY' 
    and worklog.recordkey in 
      (select wonum from woactivity where parent ='M2176'))
  OR
  (worklog.class ='WORKORDER'
    and worklog.recordkey in
      (select wonum from workorder where wonum = 'M2176'));

查询2

在这里,我也改变了第二个条件 worklog.recordkey ,来自 =in ```
select * from worklog
where (worklog.class='ACTIVITY'
and worklog.recordkey in
(select wonum from woactivity where parent='M2176'))
or (worklog.class='WORKORDER'
and worklog.recordkey in
(select wonum from workorder where wonum='M2176'))

ztyzrc3y

ztyzrc3y5#

你也可以用这个。

SELECT * 
FROM worklog w 
WHERE 1=1
    AND w.class = 'ACTIVITY' 
    AND w.recordkey IN (SELECT wonum FROM woactivity WHERE parent = 'M2176')
UNION ALL
SELECT * 
FROM worklog w 
WHERE 1=1
    AND w.class = 'WORKORDER' 
    AND w.recordkey IN (SELECT wonum FROM workorder WHERE parent = 'M2176')

相关问题