我不完全确定如何标题我的问题,如果有人知道更好的标题,请随时编辑它。
基本上我有问题,我不知道该怎么做。
我有一个包含送货地址和帐单地址的数据库。如果送货地址为空,我希望它显示帐单地址。我使用以下方法实现了这一目标:
SELECT DELIVERYADDRESS AS "Address"
FROM SHOPORDER so
UNION
SELECT BILLINGADDR AS "Address"
FROM CUSTOMER
这样有效。我还需要它与其订单“连接”。所以我这样做:
SELECT ORDID FROM SHOPORDER
我想要的是我的桌子看起来像
| ORDID | ADDRESS(如果DeliveryAddress为null,则为DeliveryAddress或BillingAddress)
请注意,我的问题表指出我必须使用联合。我试过这个:
SELECT ORDID, (SELECT DELIVERYADDRESS FROM SHOPORDER
UNION
SELECT BILLINGADDR FROM CUSTOMER)
FROM SHOPORDER
但它不起作用。我已经尝试了一个小时了,我无法弄明白。我已经尝试过内连接,左连接,右连接等等。我只是想不出来。有谁有想法吗?感谢。
答案 0 :(得分:1)
您可以使用coalesce:
从中选择ordid,coalesce(deliveryaddress,billingaddress) shoporder使用(customerid)加入客户
假设customerid是连接两个表的字段。 Coalesce非常简单:如果第一个参数为null,则使用第二个参数。
- DMG
答案 1 :(得分: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
)
答案 2 :(得分: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
答案 3 :(得分: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