簡體   English   中英

查詢問題:是否有更好的方法從一個表中選擇所有記錄,以及從另一表中選擇不匹配的記錄?

[英]Query question: Is there a better way to select all records from one table, along with unmatched records from another table?

考慮以下:

**Customers**
CustomerId (PK)
LastName
FirstName
Address1
City
State
Zip

**CustomerMailingAddresses**
CustomerId (PK)/(FK)
Address1
City
State
Zip

基本上,兩個表之間存在一對一的關系。 但是,並非Customer中的每個客戶記錄在CustomerMailingAddresses表中都有一個條目。 我正在嘗試使用T-SQL(Sql Server 2008)生成客戶名稱和地址列表。 但是,我只想從CustomerMailingAddresses返回地址,以及從Customer中返回的所有地址,這些地址在CustomerMailingAddresses中沒有每個CustomerId的對應條目。 換句話說,CustomerMailingAddresses中的條目(如果有的話)將充當客戶中地址的替代。

我碰壁了,因為我嘗試過的所有查詢都不起作用。 我願意接受任何建議。

一種選擇是使用COALESCE

select
    c.CustomerId,
    COALESCE(m.Address1, c.Address1) as Address1,
    COALESCE(m.City, c.City) as City,
    COALESCE(m.State, c.State) as State,
    COALESCE(m.Zip, c.Zip) as Zip
from Customers c
left join CustomerMailingAddresses m on m.CustomerId = c.CustomerId

怎么樣

SELECT * FROM Customers
MINUS
SELECT Customers.*
       FROM Customers, CustomerMailingAddresses
       WHERE Customers.CustomerId = CustomerMailingAddresses.CustomerId

(對不起,如果我的SQL有點生銹)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM