我在其中一个查询中有两个sql查询,我执行左外部联接,两者都应该返回相同的记录no,但返回的任何行在这两个sql查询中都是不同的。
select Txn.txnRecNo
from Txn
inner join Person on Txn.uwId = Person.personId
full outer join TxnInsured on Txn.txnRecNo = TxnInsured.txnRecNo
left join TxnAdditionalInsured on Txn.txnRecNo = TxnAdditionalInsured.txnRecNo
where Txn.visibleFlag=1
and Txn.workingCopy=1 交还20份纪录
select Txn.txnRecNo
from Txn
inner join Person on Txn.uwId = Person.personId
full outer join TxnInsured on Txn.txnRecNo = TxnInsured.txnRecNo
where Txn.visibleFlag=1
and Txn.workingCopy=1交回15份纪录
发布于 2016-03-09 07:16:29
我怀疑TxnAdditionalInsured表有重复记录。使用distinct
select distinct Txn.txnRecNo
from Txn
inner join Person on Txn.uwId = Person.personId
full outer join TxnInsured on Txn.txnRecNo = TxnInsured.txnRecNo
left join TxnAdditionalInsured on Txn.txnRecNo = TxnAdditionalInsured.txnRecNo
where Txn.visibleFlag=1
and Txn.workingCopy=1发布于 2016-03-09 07:49:37
left联接将在结果集中至少从联接的左侧生成所有行。
但是,如果您的联接条件是,右侧有多行与左边的特定行相匹配,则该左行将在结果中出现多次(与右行匹配的次数相同)。
因此,如果结果是意外的,您的连接条件就不会像它们所需要的那样严格,或者您没有像您想象的那样理解您的数据。
与其他答案不同,我不建议仅仅添加distinct --我建议您调查您的数据并确定您的ON子句是否需要加强,或者您的数据实际上是否不正确。将distinct添加到“使结果看起来正确”通常是一个糟糕的决定--更愿意进行调查并编写正确的查询。
发布于 2016-03-09 07:13:40
试试这个:
select distinct Txn.txnRecNo --> added distinct here
from Txn
inner join Person on Txn.uwId = Person.personId
full outer join TxnInsured on Txn.txnRecNo = TxnInsured.txnRecNo
left join TxnAdditionalInsured on Txn.txnRecNo = TxnAdditionalInsured.txnRecNo
where Txn.visibleFlag=1
and Txn.workingCopy=1 https://stackoverflow.com/questions/35885169
复制相似问题