SQL从不同的表

时间:2017-07-27 20:16:47

标签: sql-server parent-child

我有2个表:Customer和SubAccount。
Customer(customerId, customerName, address, city, state)
SubAccount(subAccountID, subAccountName, customerID, subAddress, subCity, subState)
我想选择父客户和他们的每个子账户,如下所示:

+------------+---------------+
| 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 个答案:

答案 0 :(得分:1)

UNION ALL您现有的查询,其中一个简单的查询从Customers表中选择CustomerName和NULL(AS SubAccount)(无连接)。