【问题标题】:SQL select parent and child from different tablesSQL从不同的表中选择父子
【发布时间】:2017-07-27 20:16:46
【问题描述】:

我有 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  |
+------------+---------------+

选择的正确方法是什么?

【问题讨论】:

    标签: sql-server parent-child


    【解决方案1】:

    使用从客户表中选择 CustomerName 和 NULL (AS SubAccount) 的简单查询来联合所有现有查询(无联接)。

    【讨论】:

    • 不错的简单解决方案
    • 这有效,除非客户没有子帐户,然后 customerName 出现两次
    • 执行UNION 而不是UNION ALL 就像我想要的那样工作。
    • 或者使用 INNER JOIN 而不是 LEFT JOIN 进行 UNION ALL。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多