读书人

查询SQL语句哪位高手能解决

发布时间: 2012-01-15 22:57:49 作者: rapoo

查询SQL语句谁能解决?
表结构如下:
table1
idtypename table2id
2张三7, 1
5王五107, 17, 7
6木头六2, 1, 7
9李四17

table2
idtypename
1木头
2食品
7棒椴
17可可
107杯子


查询结果如下:

viewtable
idtable1typenametable2typename
2张三棒椴
2张三木头
5王五杯子
5王五可可
5王五棒椴
6木头六食品
6木头六可可
6木头六棒椴
9李四可可

目的就是把table1表中的table2id里的每个以逗号拆分项当做一条记录来显示出来!

[解决办法]
参考这个:

create table tblTest(PdID int,PdName varchar(100))

insert tblTest
select 1, 'A10 ' union all
select 2, 'A20,A20S ' union all
select 3, 'A30,A30K,A30M ' union all
select 4, 'A301 ' union all
select 5, 'A301M '
select * from tblTest
go

-- 建立一个辅助的临时表
SELECT TOP 8000
id = identity(int,1,1)
INTO # FROM syscolumns a, syscolumns b

SELECT
A.PdID,
PdName = SUBSTRING(A.PdName, B.ID, CHARINDEX( ', ', A.PdName + ', ', B.ID) - B.ID)
FROM tblTest A, # B
WHERE SUBSTRING( ', ' + a.PdName, B.id, 1) = ', '
ORDER BY 1,2
GO

DROP TABLE tblTest, #
[解决办法]

create table A(id int, typename varchar(20), table2id varchar(20))
insert A select 2, '张三 ', '7,1 '
union all select 5, '王五 ', '107,17,7 '
union all select 6, '木头六 ', '2,1,7 '
union all select 9, '李四 ', '17 '
create table B(id int, typename varchar(20))
insert B select 1, '木头 '
union all select 2, '食品 '
union all select 7, '棒椴 '
union all select 17, '可可 '
union all select 107, '杯子 '

select A.id, A.typename, B.typename
from A
inner join B on charindex( ', '+rtrim(B.id)+ ', ', ', '+A.table2id+ ', ')> 0

--result
id typename typename
----------- -------------------- --------------------
2 张三 木头
2 张三 棒椴
5 王五 棒椴
5 王五 可可
5 王五 杯子
6 木头六 木头
6 木头六 食品
6 木头六 棒椴
9 李四 可可

(9 row(s) affected)

读书人网 >SQL Server

热点推荐