2017-07-27 54 views
2

我有2個表:Customer和SubAccount。
Customer(customerId, customerName, address, city, state)
SubAccount(subAccountID, subAccountName, customerID, subAddress, subCity, subState)
我想選擇父客戶及其每個子賬戶的,像這樣:SQL從不同的表中選擇父和子

+------------+---------------+ 
| Customer | SubAccount | 
+------------+---------------+ 
| Customer1 | null   | 
| Customer1 | SubAccount1 | 
| Customer1 | SubAccount2 | 
| Customer2 | null   | 
| Customer2 | SubAccount1 | 
| Customer3 | null   | 
| Customer3 | SubAccount1 | 
+------------+---------------+ 

然而,做一個簡單的

SELECT Customer.CustomerName, SubAccount.subAccountName 
FROM Customer 
LEFT JOIN SubAccount ON SubAccount.CustomerId = Customer.CustomerID 

不起作用。它只顯示

+------------+---------------+ 
| Customer | SubAccount | 
+------------+---------------+ 
| Customer1 | SubAccount1 | 
| Customer1 | SubAccount2 | 
| Customer2 | SubAccount1 | 
| Customer3 | SubAccount1 | 
+------------+---------------+ 

什麼是做選擇的正確方法?

回答

1

UNION將所有現有查詢與一個簡單的查詢從Customers表(不加入)中選擇CustomerName和NULL(AS SubAccount)。

+0

很簡單的解決方案 – Eli

+0

這是有效的,除非客戶沒有子賬戶,那麼customerName出現兩次 –

+0

做'UNION'而不是'UNION ALL'就像我想要的那樣工作。 –