根据来自不同表的值获取列

时间:2013-01-14 12:28:36

标签: sql sql-server

我有以下查询:

   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字段而不是另一个。

由于

1 个答案:

答案 0 :(得分: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;