CREATE TABLE [dbo].[Person](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nchar](10) NULL,
[InClub] [nvarchar](255) NULL,
CONSTRAINT [PK_Person] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
CREATE TABLE [dbo].[PersonClub](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ClubName] [nvarchar](50) NULL,
CONSTRAINT [PK_PersonClub] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
注意:InClub字段是表示该人加入了哪些社团 用 ','隔开。(我个人不建议这样设计表,但是有时候确实有这种情况)
1 张三 1,3,5
2 李四 2,3,4
3 王无 3,2
1 编程协会
2 羽毛球协会
3 武术协会
4 旋律社
5 动漫社
6 摄影社
SELECT *
FROM Person D
CROSS APPLY (
SELECT STUFF((
SELECT ',' + C.ClubName
FROM Person A
CROSS APPLY f_split(A.InClub, ',') B
LEFT JOIN PersonClub c ON c.ID = B.a
WHERE A.ID = D.ID
FOR XML path('')
), 1, 1, '') AS ClubName
) E
结果
1 张三 1,3,5 编程协会,武术协会,动漫社
2 李四 2,3,4 羽毛球协会,武术协会,旋律社
3 王无 3,2 武术协会,羽毛球协会
备注: f_split 表值函数是在网上找的,用于分割字符串为临时表,这里不做讨论。