为什么“价值太多”?

时间:2018-04-04 01:20:15

标签: sql

master@{1.day.ago}

1 个答案:

答案 0 :(得分:0)

问题是not in

select MATNR, HKL
from (select MATNR, HKL
      from BESTAND
      where LOK_NR > 1 and BEST_FREI = 0
      union
      select MATNR, HKL
      from BESTAND
      where LOK_NR = 1 and BEST_FREI > 0
     )
WHERE MATNR NOT IN (select MATNR from SONDER_AUFTRAG where GREIFLOK = 'J' )
GROUP BY MATNR, HKL
ORDER BY MATNR, HKL ;

我认为查询可以简化为:

select distinct MATNR, HKL
from BESTAND b
where ((LOK_NR > 1 and BEST_FREI = 0) or
       (LOK_NR = 1 and BEST_FREI > 0)
      ) and
      not exists (select 1
                  from SONDER_AUFTRAG sa
                  where sa.MATNR = b.MATNR and GREIFLOK = 'J'
                 )
order by MATNR, HKL ;

注意:

  • 最好删除union,特别是如果or足够。
  • uniongroup by都会删除查询中的重复项。
  • not exists优于带有子查询的not in,因为后者不直观地处理NULL值。