日期:2014-05-17  浏览次数:20395 次

一个头疼的表连接
有table1,table2两表,table1中的qid存的是tbale2的id,现在想把这两张表关联起来

create table table1(
id int,
qid varchar(100)
)

create table table2(
id int,
name varchar(100)
)

insert into table2 values(1, '张三');
insert into table2 values(2, '李四');
insert into table2 values(3, '王五');

insert into table1 values(1, '1,');
insert into table1 values(2, '1,2,3,');
insert into table1 values(3, '2,3,');
表连接 多对多 一对多

------解决方案--------------------

SELECT  id ,
        SUBSTRING([qid], number, CHARINDEX(',', [qid] + ',', number) - number) AS [qid]
FROM    table1 a ,
        master..spt_values
WHERE   number >= 1
        AND number < LEN([qid])
        AND type = 'p'
        AND SUBSTRING(',' + [qid], number, 1) = ','
        
/*
id          qid
----------- ----------------------------------------------------------------
1           1
2           1
2           2
2           3
3           2
3           3
*/
        用这个你想怎么关联?
------解决方案--------------------

with wt as
(
SELECT A.id, B.qid
FROM(
    SELECT id, [qid] = CONVERT(xml,'<root><v>' + REPLACE([qid], ',', '</v><v>') + '</v></root>') FROM table1
)A
OUTER APPLY(
    SELECT qid = N.v.value('.', 'varchar(100)') FROM A.[qid].nodes('/root/v') N(v)
)B
)
select wt.id as table1id ,table2.id as table2id,table2.name from table2,wt 
where table2.id = wt.qid and wt.qid <>''

------解决方案--------------------
select a.id,b.name from table1 a,table2 b where 
a.qid like '%'+convert(varchar(50),b.id)+'%' order by a.id