我有一个存储基本站点信息的表,另一个存储站点地址的表,以及第三个用于电话的表。我的电话表包含电话号码和号码类型。
我想要的是获取我的网站信息,以及主要的联系电话和传真号码。到目前为止,我的陈述看起来像这样:
SELECT site.isiteid,
site.iclientid,
csitecode,
csitename,
binactive,
caddress1,
caddress2,
ccity,
cstateid,
czip,
icountryid,
cattention,
cemail,
cnumber,
cextension
FROM dbo.site
INNER JOIN dbo.address
ON dbo.site.isiteid = dbo.address.isiteid
AND (site.isiteid = 2)
LEFT JOIN dbo.phone
ON dbo.site.isiteid = dbo.phone.isiteid
AND (dbo.phone.iphtypeid = 1)
除了传真号码(dbo.phone.iphtypeid = 3)之外,这还能获取我需要的所有信息。有没有办法在名为[fax]的结果中添加另一列,并在site.isiteid = phone.isiteid AND phone.iphtypeid = 3时填充它?因此,返回的最后4列将是[cemail][cnumber][cextension][cfax].
分辨
感谢所有三位回答的人。所有答案都是相似的,所以我选择了最详细解释的答案。我确实需要将表名添加到cnumber引用和cextension以避免歧义。谢谢你的回复!
答案 0 :(得分:2)
添加另一个JOIN
子句
LEFT JOIN dbo.phone f
ON dbo.site.isiteid = f.isiteid
AND f.iphtypeid = 3
然后,您将f.cfax添加到SELECT
列表中。
给其他表别名也可能是好的,这样你就可以区分哪些列来自哪些表。
答案 1 :(得分:1)
是的,您可以通过向dbo.phone
添加其他联接来完成此操作。要区分这两种用途,您需要为第二个连接添加别名。所以,像:
SELECT site.isiteid,
site.iclientid,
csitecode,
csitename,
binactive,
caddress1,
caddress2,
ccity,
cstateid,
czip,
icountryid,
cattention,
cemail,
phone.cnumber,
phone.cextension,
phone_fax.cnumber AS cfax
FROM dbo.site
INNER JOIN dbo.address
ON dbo.site.isiteid = dbo.address.isiteid
AND (site.isiteid = 2)
LEFT JOIN dbo.phone
ON dbo.site.isiteid = dbo.phone.isiteid
AND (dbo.phone.iphtypeid = 1)
LEFT JOIN dbo.phone AS phone_fax
ON dbo.site.isiteid = phone_fax.isiteid
AND (phone_fax.iphtypeid = 3)
答案 2 :(得分:1)
你可以做类似的事情,即使我不确定你是如何定义表的。
SELECT site.isiteid,
site.iclientid,
csitecode,
csitename,
binactive,
caddress1,
caddress2,
ccity,
cstateid,
czip,
icountryid,
cattention,
cemail,
cnumber,
cextension,
CASE WHEN C.iphtypeid = 3 THEN C.cnumber ELSE NULL END [cfax]
FROM dbo.site A
INNER JOIN dbo.address
ON dbo.site.isiteid = dbo.address.isiteid
AND (site.isiteid = 2)
LEFT JOIN dbo.phone C
ON A.isiteid = C.isiteid