我自己无法弄清楚这一点。希望有人能帮助我。
我有三个表:users
,cards
,referees
和users_cards
用户:
id | userName | referee_id
----------------------------
1 | u1 | 1
2 | u2 | 1
3 | u3 | 2
裁判员:
id | refName
--------------
1 | ref1
2 | ref2
牌:
id | cardName
--------------
1 | card1
2 | card2
Users_Cards:
user_id | card_id | color | number
-------------------------------------------
1 | 1 | red | 123
1 | 2 | yellow | 312
2 | 2 | yellow | 523
3 | 1 | red | 344
我想得到的结果是:
id | userName | refName | cards
1 | u1 | ref1 | card1: red (123), card2: yellow (312)
2 | u2 | ref1 | card2: yellow (523)
3 | u3 | ref2 | card1: red (344)
等等......
当用户拥有多张卡时,我所能获得的只是多行。那么如何将它们组合起来呢。
感谢任何能帮助我的人!'
编辑:
目前我只使用LEFT JOIN
s
SELECT UserName, refName cardName, color, number,
FROM users
LEFT JOIN referees ON users.referee_id = referees.id
LEFT JOIN users_cards ON users.id = users_cards.user_id
LEFT JOIN cards ON dbo.users_cards.card_id = cards.id
答案 0 :(得分:0)
我认为没有简单的方法来格式化表的结果并将其附加到结果中。 您可以尝试使用以下内容执行存储过程:
CREATE TABLE #temp
(
user_id int,
CardString nvarchar(50)
)
CREATE TABLE #userCards
(
user_id int,
CardsList nvarchar(50)
)
DECLARE @UserID int,
@cardName nvarchar(50),
@cardList nvarchar(250)
INSERT INTO #temp
SELECT user_id, cardName + ': ' + color + ' (' + number + ')'
FROM User_Cards AS UC
INNER JOIN Cards AS C ON C.card_id = UC.card_id
WHILE EXISTS (SELECT * FROM #temp)
BEGIN
SELECT TOP(1) @UserID = user_id FROM #temp
SET @cardList = ''
WHILE EXISTS (SELECT * FROM #temp WHERE user_id = @UserID)
BEGIN
SELECT TOP(1) @cardName = [CardString] FROM #temp WHERE user_id = @UserID
IF @cardList <> ''
SET @cardList = @cardList + ', '
SET @cardList = @cardList + @cardName
END
INSERT INTO #userCards
VALUES (user_id, @cardList)
END
SELECT users.id, users.userName, referees.refName, CardsList
FROM users
LEFT JOIN referees ON users.referee_id = referees.id
LEFT JOIN #userCards ON #userCards.card_id = users.user_id
DROP TABLE #userCards
DROP TABLE #temp
这将返回您想要的内容。 您还可以定义聚合函数(请参阅http://msdn.microsoft.com/en-us/library/ms190678.aspx)
答案 1 :(得分:0)
SELECT users.id, UserName, refName,
cards = (
SELECT
STUFF((
SELECT ', card' + CAST(ROW_NUMBER() OVER (ORDER BY cards.id) AS VARCHAR)
+': '+ color + '(' + CAST(number AS VARCHAR) +')'
FROM
users_cards
LEFT JOIN cards ON dbo.users_cards.card_id = cards.id
WHERE users.id = users_cards.user_id
FOR XML PATH('')), 1, 1, '')
)
FROM users
LEFT JOIN referees ON users.refereeid = referees.id