我有兩張表我想加入。一個包含名爲「客戶」的客戶。另一張表「Customeraccounts」。這些表格與客戶ID有關係。喜歡這個。用sql連接表
Customers
1, john, Smith
CustomerAccounts
1, 1, 12345678
2, 1, 98765432
我如何加入表,輸出將是:
1, john, smith, 12345678, 98765432
我有兩張表我想加入。一個包含名爲「客戶」的客戶。另一張表「Customeraccounts」。這些表格與客戶ID有關係。喜歡這個。用sql連接表
Customers
1, john, Smith
CustomerAccounts
1, 1, 12345678
2, 1, 98765432
我如何加入表,輸出將是:
1, john, smith, 12345678, 98765432
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 |名稱
我認爲它會工作
也許這會爲你工作:
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
在的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?
你嘗試過什麼?什麼沒有用?你知道你需要加入,你看看JOIN子句的文檔嗎? – Oded 2011-06-16 09:27:30
@Oded:JOIN不足以做到這一點。 @espen:你爲什麼想在SQL中創建這種輸出?這是應用程序層的事情,而不是數據庫。 – Tomalak 2011-06-16 09:30:42
我已經嘗試了所有可以找到的連接子句,我想我通過內部連接正確地完成連接。但我得到 約翰,史密斯,12345678 約翰,史密斯,98765432 我的目標是讓一個客戶的所有帳戶在一行。 – espen 2011-06-16 09:31:29