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

字段包含查找问题
表1:
roleId     funcId
    1               2
    2               3
    1               5
    1               6
    2               1
 3      5

表2:
roleId     userXM
    1,2,         aa
    2               bb
如何查找userXM为 "aa "的记录对应表1中的funcId?
   


------解决方案--------------------
select a.* from 表1 a,表2 b where charindex( ', '+rtrim(a.roleId)+ ', ' , ', '+b.roleId+ ', ')> 0 and b.userXM= 'aa '
------解决方案--------------------
create table A (roleId varchar(10), funcId varchar(10))
insert into A values( '1 ', '2 ')
insert into A values( '2 ', '3 ')
insert into A values( '1 ', '5 ')
insert into A values( '1 ', '6 ')
insert into A values( '2 ', '1 ')
insert into A values( '3 ', '5 ')
create table B (roleId varchar(10), userXM varchar(10))
insert into B values( '1,2 ', 'aa ')
insert into B values( '2 ' , 'bb ')
go

select a.* from a,b where b.userxm = 'aa ' and charindex( ', '+a.roleid+ ', ', ', '+b.roleid+ ', ') > 0

drop table A,B
/*
roleId funcId
---------- ----------
1 2
2 3
1 5
1 6
2 1
(所影响的行数为 5 行)
*/

------解决方案--------------------
create table 表1(roleId int, funcId int)
insert 表1
select 1,2
union select 2,3
union select 1,5
union select 1,6
union select 2,1
union select 3,5

create table 表2(roleId varchar(10), userXM varchar(10))
insert 表2
select '1,2, ', 'aa '
union select '2 ', 'bb '


select b.*
from 表2 a inner join 表1 b on charindex( ', '+rtrim(b.roleId)+ ', ' , ', '+rtrim(a.roleId)+ ', ')> 0
where userXM= 'aa '


drop table 表1,表1
------解决方案--------------------
declare @a table(roleid int,funcid int)
insert @a
select 1,2
union all
select 2, 3
union all
select 1,5
union all
select 1,6
union all
select 2 ,1
union all
select 3, 5

declare @b table(roleId varchar(20),userXM varchar(20))
insert @b
select '1,2 ', 'aa '
union all
select '2 ' , ' bb '


select * from @a a,@b b where charindex(cast(a.roleid as varchar),b.roleId)> 0 and b.userXM= 'aa '

/*

(所影响的行数为 2 行)

roleid funcid roleId userXM
----------- ----------- -------------------- --------------------
1 2 1,2 aa
2 3 1,2 aa
1 5 1,2 aa
1 6 1,2 aa
2 1 1,2 aa