如何查询具有一个匹配和一个不匹配字段的行

时间:2014-03-20 01:43:23

标签: mysql sql

鉴于tblAllKeys(fldKey, fldCode)tblModKeys(fldKey, fldCode)的数据位于tblAllKeys ...

fldCode   fldKey
dba       1
dba       2
dba       3
dba       4
cde       1
cde       2
cde       3
tblModKeys ...

fldCode   fldKey
dba       1
dba       2
dba       3
dba       4
dba       5
dba       6
cde       1
cde       2
cde       3
cde       4

我想从tblModKeys返回行,其中fldCode与tblAllKeys.fldCode匹配,但tblAllKeys.fldCode中不存在tblModKeys.fldKey。我有兴趣知道是否有办法专门用连接做到这一点?

2 个答案:

答案 0 :(得分:2)

这有点棘手,但您的样本数据并不公平。你需要一个像mod键表中fgh, 5这样的行的例子,它不在all key表中。

我们的想法是使用left outer join,但仅限于fldcode列。这样,您可以检查此代码是否匹配。然后进行聚合以在fldkey;

上查找匹配项
select mk.*
from tblModkeys mk left outer join
     tblAllkeys ak
     on mk.fldcode = ak.fldcode
group by mk.fldcode, mk.fldkey
having sum(ak.fldkey = mk.fldkey) = 0 and sum(ak.fldcode is null) = 0;

答案 1 :(得分:2)

SELECT DISTINCT mk.*
FROM tblModkeys mk
JOIN tblAllkeys ak1 ON mk.fldcode = ak1.fldcode -- fldcode exists in tblAllkeys
LEFT JOIN tblAllkeys ak2 ON mk.fldkey = ak2.fldkey
WHERE ak2.fldkey IS NULL -- fldkey does not exist in tblAllkeys