2

我必须根据可以为空的值选择相应的列来加入。详细地:

SELECT shoporders.orderid, 
   shopaddresses.companyname, 
   shopaddresses.firstname, 
   shopaddresses.lastname, 
   shopaddresses.address1,  
FROM   shoporders 
   INNER JOIN shopaddresses 
           ON shoporders.InvoiceAddressId = shopaddresses.addressid
where orderid = 110
order by shoporders.createddate desc

如果 shoporders.InvoiceAddressId 为空,那么我必须使用 shoporders.DeliveryAddressId

有什么线索吗?

提前致谢

4

3 回答 3

6
ON coalesce(shoporders.InvoiceAddressId, shoporders.DeliveryAddressId) = shopaddresses.addressid
于 2012-09-25T15:02:25.380 回答
3

你可以试试

SELECT shoporders.orderid, 
   shopaddresses.companyname, 
   shopaddresses.firstname, 
   shopaddresses.lastname, 
   shopaddresses.address1,  
FROM   shoporders 
   INNER JOIN shopaddresses 
           ON COALESCE (shoporders.InvoiceAddressId, shoporders.DeliveryAddressId)  = shopaddresses.addressid
where orderid = 110
order by shoporders.createddate desc

编辑:有关合并的定义,请参阅MSDN。总结如下

返回其参数中的第一个非空表达式。COALESCE(expression1,...n)等价于以下CASE表达式:

CASE

   WHEN (expression1 IS NOT NULL) THEN expression1

   WHEN (expression2 IS NOT NULL) THEN expression2

   ...

   ELSE expressionN

END
于 2012-09-25T15:02:49.957 回答
0

你可以试试

 SELECT shoporders.orderid, 
       shopaddresses.companyname, 
       shopaddresses.firstname, 
       shopaddresses.lastname, 
       shopaddresses.address1,  
       FROM   shoporders 
       INNER JOIN shopaddresses 
       ON( 
          (shoporders.InvoiceAddressId IS NOT NULL  
                  AND shoporders.InvoiceAddressId = shopaddresses.addressid)
          OR (shoporders.DeliveryAddressId = shopaddresses.addressid) 
          )

       WHERE orderid = 110
       ORDER BY shoporders.createddate DESC
于 2012-09-25T15:05:15.040 回答