首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

遇见一个不好解决的有关问题

2012-09-05 
遇见一个不好解决的问题有一个表a字段iddmcityId------------------------------数据1新疆1,2数据2西藏2,3

遇见一个不好解决的问题
有一个表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

[解决办法]

SQL code
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)*/ 

热点排行
Bad Request.