如何优化此查询?我尝试过使用LEFT JOIN
条款,但仍然需要至少3秒钟。
SELECT DISTINCT MBLNR
FROM MKPF
WHERE MANDT='368'
AND XBLNR = '0150525913'
AND MBLNR NOT IN ( SELECT DISTINCT SMBLN FROM MSEG WHERE XBLNR_MKPF = '0150525913' )
使用LEFT JOIN
后,仍需要3秒才能获得结果:
SELECT DISTINCT A.MBLNR
FROM MKPF AS A
LEFT JOIN MSEG AS B ON B.XBLNR_MKPF=A.XBLNR AND A.MBLNR <> B.SMBLN
WHERE A.XBLNR = '0150525913'
使用LEFT OUTER JOIN
确实需要很长时间才能返回行。
感谢。
答案 0 :(得分:1)
第一个查询的正确左外连接公式为:
SELECT DISTINCT A.MBLNR
FROM MKPF A LEFT JOIN
MSEG B
ON B.SMBLN = A.MBLNR AND AND B.XBLNR_MKPF = '0150525913'
WHERE A.XBLNR = '0150525913' and A.MANDT='368' and B.SMBLN is null;
根据表格的大小,3秒可能是合理的。但是,您可以使用索引加快查询速度。此查询提供了一些索引:MKPF(XBLNR, MANDT, MBLNR)
和MSEG(XBLNR_MKPF, SMBLN)
。
答案 1 :(得分:0)
虽然直观,但“不在”很慢。所以,改变这个:
AND MBLNR NOT IN
( SELECT DISTINCT SMBLN FROM MSEG WHERE XBLNR_MKPF = '0150525913' )
到
AND MBLNR IN
(SELECT DISTINCT MBLNR
FROM MKPF
WHERE MANDT='368'
AND XBLNR = '0150525913'
except
SELECT DISTINCT SMBLN
FROM MSEG
WHERE XBLNR_MKPF = '0150525913'
)
答案 2 :(得分:0)
为什么你使用distinct和left。如果他们确实需要那么ok。或者你可以使用内部连接而不是明显的。特别是子查询不需要不同。
you can try not exists
SELECT MBLNR
FROM MKPF
WHERE MANDT='368'
AND XBLNR = '0150525913'
AND NOT exists ( SELECT SMBLN FROM MSEG WHERE XBLNR_MKPF = '0150525913' )