我有以下查询:
SELECT pn.PhoneId,
pn.CountryId,
c.ITUCode,
pn.AreaCode,
pn.PhoneNumber,
pn.PhoneExtension,
pn.PhoneNumberTypeId,
pnt.PhoneNumberType,
pn.Comments,
ppn.IsPrimaryNumber,
cpn.IsPrimaryNumber
FROM PhoneNumbers AS pn
INNER JOIN PeoplePhoneNumbers AS ppn ON ppn.PhoneId = pn.PhoneId
INNER JOIN CompanyPhoneNumbers AS cpn ON cpn.PhoneId = pn.PhoneId
INNER JOIN Countries AS c ON c.CountryId = pn.CountryId
INNER JOIN PhoneNumberTypes AS pnt ON pnt.PhoneNumberTypeId = pn.PhoneNumberTypeId
WHERE pn.PhoneId = @PhoneId
ORDER BY ppn.IsPrimaryNumber DESC, pnt.PhoneNumberType
现在,您可以通过提取IsPrimaryKey
我必须使用两个不同的innerjoins
并从中获取两个值。
其中一个是null
,而其他人的价值总是如此。
我可以将此查询更改为单个innerjoin
联接,然后从中获取单个IsPrimaryNumber
字段而不是另一个。
由于
答案 0 :(得分:0)
LEFT JOIN
两个表ppn
,cpn
和COALESCE
将它们放在一列中,如下所示:
SELECT
pn.PhoneId,
pn.CountryId,
c.ITUCode,
pn.AreaCode,
pn.PhoneNumber,
pn.PhoneExtension,
pn.PhoneNumberTypeId,
pnt.PhoneNumberType,
pn.Comments,
COALESCE(ppn.IsPrimaryNumber, cpn.IsPrimaryNumber) IsPrimaryNumber
FROM PhoneNumbers AS pn
INNER JOIN Countries AS c ON c.CountryId = pn.CountryId
INNER JOIN PhoneNumberTypes AS pnt
ON pnt.PhoneNumberTypeId = pn.PhoneNumberTypeId
LEFT JOIN PeoplePhoneNumbers AS ppn ON ppn.PhoneId = pn.PhoneId
LEFT JOIN CompanyPhoneNumbers AS cpn ON cpn.PhoneId = pn.PhoneId
WHERE pn.PhoneId = @PhoneId
ORDER BY ppn.IsPrimaryNumber DESC, pnt.PhoneNumberType;