日期:2014-05-18  浏览次数:20499 次

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

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


查询结果如下:

viewtable
id table1typename table2typename
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)