2

这是我的查询示例:

SELECT ...
TRIM(eml.fxeml1) as "Email Address"
FROM pfship

LEFT JOIN mstfxem fax
ON fax.fxco=pfship.cshco AND fax.fxdiv=pfship.cshdiv AND fax.fxsold=pfship.cshsld
AND fax.fxtype='C' AND TRIM(fax.fxfax1) <> '' AND fax.fxdept LIKE '*F%'

LEFT JOIN mstfxem eml
ON eml.fxco=pfship.cshco AND eml.fxdiv=pfship.cshdiv AND eml.fxsold=pfship.cshsld
AND eml.fxtype='C' AND TRIM(eml.fxeml1) <> '' AND eml.fxdept LIKE '*E%'

WHERE ((pfship.cshco || '/' || pfship.cshdiv) = ?)
  AND (? = '*ALL' OR CAST(cshsld AS CHAR(15)) = ?) 
  AND ...
  ORDER BY TRIM(cshnme)

此查询应返回 9 条记录。当我删除:

LEFT JOIN mstfxem fax
ON fax.fxco=pfship.cshco AND fax.fxdiv=pfship.cshdiv AND fax.fxsold=pfship.cshsld
AND fax.fxtype='C' AND TRIM(fax.fxfax1) <> '' AND fax.fxdept LIKE '*F%'

LEFT JOIN mstfxem eml
ON eml.fxco=pfship.cshco AND eml.fxdiv=pfship.cshdiv AND eml.fxsold=pfship.cshsld
AND eml.fxtype='C' AND TRIM(eml.fxeml1) <> '' AND eml.fxdept LIKE '*E%'

我得到了 9 条记录,但有了它,我得到了 360 条记录。我的加入有什么问题?

谢谢

我认为问题是 1 人可以有很多电子邮件或传真,如何将结果分组为每条记录 1 个字符串,这样我最终只有 9 条记录?

4

1 回答 1

0

您的联接没有任何问题,表之间存在一对多的关系。

根据您的需要,有几种技术。首先是派生表。编写一个查询以从一对多表中仅选择一条记录(您的要求应指定要选择的记录)。而是加入那个。或者您可以在左连接上设置更多条件以仅获得一条记录。这些技术的一些示例:

select t1.field1, t2.email
from table1 t1 
join (select myid, max(email) as email from table2 group by myid) t2 
  on t1.myid = t2.myid

或者

select t1.field1, t2.email
from table1 t1 
Left join from table2  t2 
  on t1.myid = t2.myid and t2.active = 1

Or if you want all of the emails in a comma delimited list, that code is database specific and you would need to let us know which database backend you are using.

于 2012-08-09T15:17:04.717 回答