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 |
+------------+---------------+
什么是做选择的正确方法?
很简单的解决方案 – Eli
这是有效的,除非客户没有子账户,那么customerName出现两次 –
做'UNION'而不是'UNION ALL'就像我想要的那样工作。 –