以下是我的查询示例:
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个记录?
答案 0 :(得分: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
或者,如果您希望所有电子邮件都位于逗号分隔列表中,则该代码是特定于数据库的,您需要告诉我们您使用的是哪个数据库后端。