sql
2012-08-09 60 views 2 likes 
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條?

+0

請提供樣本數據。 – RedFilter 2012-08-09 15:17:18

+1

這些名字讓我很頭疼。 'mstfxem,pfship,cshsld,cshco'? – 2012-08-09 15:31:14

+0

@ypercube這就是我每天的感受;) – jmasterx 2012-08-09 15:32:37

回答

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 

或者,如果你希望所有以逗號delimtited列表中的郵件,該代碼是特定數據庫,你需要讓我們知道哪些數據庫後端使用。

+0

我只需要9條記錄的電子郵件,我怎樣才能得到9條記錄? – jmasterx 2012-08-09 15:18:13

+0

你的意思是1人可以有很多電子郵件?如果是這樣,我怎樣才能得到他們所有的電子郵件在1字符串? – jmasterx 2012-08-09 15:19:51

+0

@Milo - 你可以刪除連接並獲得那9個你不能?或者如果他們是相同的9個電子郵件地址,重複自己只需添加'DISTINCT'' SELECT DISTINCT EmailField FROM ...' – JonH 2012-08-09 15:19:58

相關問題