0

我不完全确定如何为我的问题命名,如果有人知道更好的标题,请随时编辑。

基本上我有一个问题,我不知道该怎么做。

我有一个包含送货地址和帐单地址的数据库。如果送货地址为空,我希望它显示帐单地址。我使用以下方法实现了这一点:

SELECT DELIVERYADDRESS AS "Address"
FROM SHOPORDER so
UNION 
SELECT BILLINGADDR AS "Address"
FROM CUSTOMER

所以这行得通。我还需要将它“连接”到它的订单。所以我这样做:

SELECT ORDID FROM SHOPORDER

我想要的是我的桌子看起来像
|ORDID | ADDRESS(DeliveryAddress 或 BillingAddress,如果 DeliveryAddress 为 null)

请注意,我的问题表指出我必须使用联合。我试过这个:

SELECT ORDID, (SELECT DELIVERYADDRESS FROM SHOPORDER
    UNION 
        SELECT BILLINGADDR FROM CUSTOMER)
FROM SHOPORDER

但它不起作用。我已经尝试了一个小时,我就是想不通。我尝试过内连接、左连接、右连接等。我就是想不通。有人有什么主意吗?谢谢。

4

4 回答 4

1

您可以为此使用合并:

选择 ordid, coalesce(deliveryaddress, billingaddress) 从 shoporder 加入客户使用 (customerid)

假设 customerid 是连接两个表的字段。合并非常简单:如果第一个参数为空,则使用第二个。

--dmg

于 2013-04-28T05:13:08.200 回答
0
SELECT CUSTOMER.CustomerId,
SHOPORDER.ORDERID,
COALESCE(SHOPORDER.DELIVERYADDRESS, CUSTOMER.BILLINGADDR) AS "Address",
CASE SHOPORDER.DELIVERYADDRESS IS NOT NULL THEN 'D' ELSE 'B' END AS AddressType,
FROM CUSTOMER
INNER JOIN SHOPORDER
ON CUSTOMER.CustomerId = SHOPORDER.CustomerId
于 2013-04-28T05:32:18.673 回答
0

通过查看 mhasan 的回答,我能够让它工作:

SELECT ORDID,DELIVERYADDRESS AS "Address"
FROM SHOPORDER so
WHERE DELIVERYADDRESS IS NOT NULL
UNION 
SELECT so.ORDID, c.BILLINGADDR AS "Address"
FROM SHOPORDER so
INNER JOIN CUSTOMER c
ON so.CUSTID = c.CUSTID
WHERE so.DELIVERYADDRESS IS NULL
ORDER BY ORDID ASC
于 2013-04-28T06:29:15.653 回答
0

既然你提到 UNION 是强制性的

SELECT ORDID,DELIVERYADDRESS AS "Address"
FROM SHOPORDER 
WHERE DELIVERYADDRESS IS NOT NULL

UNION 

SELECT ORDID,BILLINGADDR AS "Address"
FROM CUSTOMER 
WHERE ORDID IN ( SELECT ORDID
                 FROM SHOPORDER 
                 DELIVERYADDRESS IS NULL
               )
于 2013-04-28T05:11:15.537 回答