我通过连接获得了以下查询:
SELECT i.PropertyCodeId, i.IndividualCode, i.LastName,
i.Firstname, i.AccountCode, acc.Name AS AccountName,
(SELECT value
FROM Relation.ContactDetail AS cd
WHERE cd.ContactDetailTypeCode = 'EMAIL'
AND cd.RelationCode = i.IndividualCode) AS Email,
adr.City, adr.ZipCode, adr.StateCode, adr.CountryCode,
'undefined' AS MemberShipID, i.TierCode AS MemberShipTier,
i.VipCode, i.Active, i.PrimaryRoleCode
FROM Relation.Individual AS i
INNER JOIN Relation.Account AS acc ON i.AccountCode = acc.AccountNumber
LEFT OUTER JOIN Relation.ContactDetail AS cd ON i.IndividualCode = cd.RelationCode
INNER JOIN Relation.Address AS adr ON i.IndividualCode = adr.RelationCode
我的问题是关于这个陈述:
(SELECT value FROM Relation.ContactDetail AS cd WHERE cd.ContactDetailTypeCode = 'EMAIL' AND cd.RelationCode = i.IndividualCode) AS Email,
运行此语句将产生1行,但在大查询中运行它会产生4行,它还会显示不是EMAIL的ContactTypes的记录。
有谁知道我做错了什么? :(
答案 0 :(得分:1)
select
之后的列中的子查询对返回的行数没有影响。如果用'hello'
替换子查询,您将看到查询仍然返回4行。
查找join
语句中四行的原因。您通常可以逐个省略连接以找到罪魁祸首。
答案 1 :(得分:1)
您正在执行子查询的同一个表上执行左连接,但左连接条件缺少限制:cd.ContactDetailTypeCode ='EMAIL'
添加此项可能会解决您的问题。也许您也可以删除子查询,只需直接从联接表中选择值
SELECT i.PropertyCodeId, i.IndividualCode, i.LastName,
i.Firstname, i.AccountCode, acc.Name AS AccountName,
cd.value AS Email,
adr.City, adr.ZipCode, adr.StateCode, adr.CountryCode,
'undefined' AS MemberShipID, i.TierCode AS MemberShipTier,
i.VipCode, i.Active, i.PrimaryRoleCode
FROM Relation.Individual AS i
INNER JOIN Relation.Account AS acc ON i.AccountCode = acc.AccountNumber
LEFT OUTER JOIN Relation.ContactDetail AS cd ON (i.IndividualCode = cd.RelationCode AND cd.ContactDetailTypeCode = 'EMAIL')
INNER JOIN Relation.Address AS adr ON i.IndividualCode = adr.RelationCode
答案 2 :(得分:0)
如果您的LEFT OUTER JOIN
返回的行多于一行,则基本表(Relation.Individual)中的行会成倍增加。
答案 3 :(得分:0)
运行此语句将产生1行,但在大查询中运行它会产生4行,它还会显示不是EMAIL的ContactTypes 的记录。
也许可能是因为你在错误的地方做了LEFT OUTER JOIN
,或者LEFT OUTER JOIN
应该是INNER JOIN
。
如果您使用LEFT JOIN
注意LEFT JOIN
两侧的哪个表,因为左侧表的所有行都将位于结果集中。也许你应该将LEFT JOIN
设置为第一个。