0

我有以下查询:

   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

现在你可以 c 来获取IsPrimaryKey我必须使用两个不同的innerjoins并从中获取两个值。

其中一个将是null,另一个将具有始终如此的值。

那么我可以将此查询更改innerjoin为他们两个的单个联接,然后IsPrimaryNumber从中获取单个字段而不是另一个字段。

谢谢

4

1 回答 1

0

LEFT JOIN这两个表ppncpnCOALESCE它们放在一列中,如下所示:

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;
于 2013-01-14T12:32:23.253 回答