SELECT NOT IN 子查询中有多个列
SELECT NOT IN with multiple columns in subquery
关于下面的说法,sltrxid 可以同时作为 ardoccrid 和 ardocdbid 存在。我想知道如何将两者都包含在 NOT IN 子查询中。
SELECT *
FROM glsltransaction A
INNER JOIN cocustomer B ON A.acctid = B.customerid
WHERE sltrxstate = 4
AND araccttype = 1
AND sltrxid NOT IN(
SELECT ardoccrid,ardocdbid
FROM arapplyitem)
我会推荐 not exists
:
SELECT *
FROM glsltransaction t
INNER JOIN cocustomer c ON c.customerid = t.acctid
WHERE
??.sltrxstate = 4
AND ??.araccttype = 1
AND NOT EXISTS (
SELECT 1
FROM arapplyitem a
WHERE ??.sltrxid IN (a.ardoccrid, a.ardocdbid)
)
请注意,我将 table 别名更改为更有意义的内容。我强烈建议在列名前加上它们所属的 table 前缀,这样查询就明确了——在没有任何指示的情况下,我在查询中将其表示为 ??
。
IN
有时优化不好。有两种子查询效率更高的情况:
SELECT *
FROM glsltransaction t
INNER JOIN cocustomer c ON c.customerid = t.acctid
WHERE
??.sltrxstate = 4
AND ??.araccttype = 1
AND NOT EXISTS (
SELECT 1
FROM arapplyitem a
WHERE ??.sltrxid = a.ardoccrid
)
AND NOT EXISTS (
SELECT 1
FROM arapplyitem a
WHERE ??.sltrxid = a.ardocdbid
)
关于下面的说法,sltrxid 可以同时作为 ardoccrid 和 ardocdbid 存在。我想知道如何将两者都包含在 NOT IN 子查询中。
SELECT *
FROM glsltransaction A
INNER JOIN cocustomer B ON A.acctid = B.customerid
WHERE sltrxstate = 4
AND araccttype = 1
AND sltrxid NOT IN(
SELECT ardoccrid,ardocdbid
FROM arapplyitem)
我会推荐 not exists
:
SELECT *
FROM glsltransaction t
INNER JOIN cocustomer c ON c.customerid = t.acctid
WHERE
??.sltrxstate = 4
AND ??.araccttype = 1
AND NOT EXISTS (
SELECT 1
FROM arapplyitem a
WHERE ??.sltrxid IN (a.ardoccrid, a.ardocdbid)
)
请注意,我将 table 别名更改为更有意义的内容。我强烈建议在列名前加上它们所属的 table 前缀,这样查询就明确了——在没有任何指示的情况下,我在查询中将其表示为 ??
。
IN
有时优化不好。有两种子查询效率更高的情况:
SELECT *
FROM glsltransaction t
INNER JOIN cocustomer c ON c.customerid = t.acctid
WHERE
??.sltrxstate = 4
AND ??.araccttype = 1
AND NOT EXISTS (
SELECT 1
FROM arapplyitem a
WHERE ??.sltrxid = a.ardoccrid
)
AND NOT EXISTS (
SELECT 1
FROM arapplyitem a
WHERE ??.sltrxid = a.ardocdbid
)