我有两张桌子,我想加入。一个包含客户,名为“客户”。另一张表“Customeraccounts”。表格与客户ID有关。像这样。
Customers
1, john, Smith
CustomerAccounts
1, 1, 12345678
2, 1, 98765432
如何将表连接到输出将是:
1, john, smith, 12345678, 98765432
答案 0 :(得分:1)
SELECT * FROM Customer RIGHT OUTER JOIN CustomerAccounts
ON Customer.customer_id=CustomerAccounts.customer_id;
答案 1 :(得分:1)
也许这对你有用:
SELECT Customers.Id,
Customers.LastName,
Customers.FirstName,
STUFF((SELECT ',' + CustomerAccounts.Number
FROM CustomerAccounts
WHERE CustomerAccounts.CustomerId = Customers.Id
FOR XML PATH('')
),1,1,'')
AS AllCustomerAccounts
FROM Customers
答案 2 :(得分:1)
在 MySQL 中,您可以
SELECT
Cust.ID
, Cust.Forname
, Cust.Name
, GROUP_CONCAT(Acc.Number) as AccNumber
FROM CustomerAccount Acc
INNER JOIN Customers Cust ON Acc.ID_Customer = Cust.ID
GROUP BY Cust.id
在 SQL服务器中,您需要对其进行一些调整并执行以下操作:
SELECT
Cust.ID,
, Cust.Forname
, Cust.Name
, AccNumber = replace
((SELECT A2.number AS [data()]
FROM CustomerAccount A2
INNER JOIN Customers C2 ON A2.ID_Customer = C2.ID
WHERE Cust.id = C2.id
ORDER BY A2.number FOR xml path('')), ' ', REQUIRED SEPERATOR)
FROM CustomerAccount Acc
INNER JOIN Customers Cust ON Acc.ID_Customer = Cust.ID
GROUP BY Cust.id, cust.Forname, cust.Name
另请参阅此问题:Simulating group_concat MySQL function in Microsoft SQL Server 2005?
答案 3 :(得分:0)
Select
Acc.ID,
Cust.Forname,
Cust.Name,
Acc.Number
From CustomerAccount Acc
Inner Join Customers Cust
On Acc.ID_CUstomer = Cust.ID
我认为你的专栏是
CustomerAccount ID | ID_Customer |编号
客户 ID |的forName |名称
我认为它会起作用