遇见一个不好解决的问题
有一个表a
字段 id dm cityId
------------------------------
数据 1 新疆 1,2
数据 2 西藏 2,3,4
表b是
字段 id cityName
------------------------------
数据 1 乌鲁木齐
数据 2 成都
数据 3 包头
数据 4 东胜
而a和b关联后要求显示为:
字段 id dm cityName cityId
--------------------------------------------------
数据 1 新疆 乌鲁木齐 1
数据 1 新疆 成都 2
数据 2 西藏 成都 2
数据 2 西藏 包头 3
数据 2 西藏 东胜 4
[解决办法]
if object_id('[a]') is not null drop table [a]gocreate table [a]([id] int, [dm] nvarchar(30),[cityId] varchar(30))goinsert into [a]select 1, N'新疆', '1,2' union allselect 2, N'西藏', '2,3,4'goif object_id('[b]') is not null drop table [b]gocreate table [b]([id] int, [cityName] nvarchar(30))goinsert into [b]select 1, N'乌鲁木齐' union allselect 2, N'成都' union allselect 3, N'包头' union allselect 4, N'东胜'goselect * from [a]select [a].[id],[a].[dm],[b].[cityName],[b].[id] cityId from [b],[a]where charindex(convert(varchar(5),[b].[id])+',',convert(varchar(5),[a].[cityId])+',')>0/*(2 row(s) affected)(4 row(s) affected)id dm cityId----------- ------------------------------ ------------------------------1 新疆 1,22 西藏 2,3,4(2 row(s) affected)id dm cityName cityId----------- ------------------------------ ------------------------------ -----------1 新疆 乌鲁木齐 11 新疆 成都 22 西藏 成都 22 西藏 包头 32 西藏 东胜 4(5 row(s) affected)*/