2017-07-27 45 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'就像我想要的那样工作。 –