ID ClassName
1 系统设置
2 留言管理
3 评论管理
A表结构:
ID UserName BasicPower
1 admin ,1,2,3,
2 Tom ,2,3,
3 Jack ,3,
想要得到这样的结构:
1 admin 系统设置,留言管理,评论管理
2 Tom 留言管理,评论管理
3 Jack 评论管理
5 个解决方案
#1
定义一个函数,能够分割basicpower字段的value,并进行替换。然后直接用一条sql语句,诸如:select username,keywordsreplace(basicpower) from A 这样的语句执行即可。
字符串分割函数请参考: http://www.cnblogs.com/jhobo/archive/2007/06/06/773858.aspx
字符串分割函数请参考: http://www.cnblogs.com/jhobo/archive/2007/06/06/773858.aspx
#2
建议A表结构:
ID UserName BasicPower
1 admin 1
2 admin 2
3 admin 3
4 Tom 2
5 Tom 3
6 Jack 3
更有利于你操作
ID UserName BasicPower
1 admin 1
2 admin 2
3 admin 3
4 Tom 2
5 Tom 3
6 Jack 3
更有利于你操作
#3
create table A(ID int,UserName nvarchar(40),BasicPower nvarchar(100))
insert into A
select 1,'admin',',1,2,3,' union all
select 2,'Tom',',2,3,' union all
select 3,'Jack',',3,'
select * from A
create table B(ID int,ClassName nvarchar(50))
insert into B
select 1,'系统设置' union all
select 2,'留言管理' union all
select 3,'评论管理'
select* from B
select id,UserName,
BasicPower=stuff((select ','+ ClassName from B
where charindex(rtrim(id)+',',A.BasicPower+',')>0 for xml path('')),1,1,'')
from A group by id,UserName,BasicPower
drop table A;
drop table B;
#4
select a.id,a.username,
GROUP_CONCAT(DISTINCT classname ORDER BY b.id asc SEPARATOR ",") as basicpower
from a,b where find_in_set(b.ID,a.basicpower)
group by a.id;
#5
谢谢大家,我还是直接存名字,不存ID了。
#1
定义一个函数,能够分割basicpower字段的value,并进行替换。然后直接用一条sql语句,诸如:select username,keywordsreplace(basicpower) from A 这样的语句执行即可。
字符串分割函数请参考: http://www.cnblogs.com/jhobo/archive/2007/06/06/773858.aspx
字符串分割函数请参考: http://www.cnblogs.com/jhobo/archive/2007/06/06/773858.aspx
#2
建议A表结构:
ID UserName BasicPower
1 admin 1
2 admin 2
3 admin 3
4 Tom 2
5 Tom 3
6 Jack 3
更有利于你操作
ID UserName BasicPower
1 admin 1
2 admin 2
3 admin 3
4 Tom 2
5 Tom 3
6 Jack 3
更有利于你操作
#3
create table A(ID int,UserName nvarchar(40),BasicPower nvarchar(100))
insert into A
select 1,'admin',',1,2,3,' union all
select 2,'Tom',',2,3,' union all
select 3,'Jack',',3,'
select * from A
create table B(ID int,ClassName nvarchar(50))
insert into B
select 1,'系统设置' union all
select 2,'留言管理' union all
select 3,'评论管理'
select* from B
select id,UserName,
BasicPower=stuff((select ','+ ClassName from B
where charindex(rtrim(id)+',',A.BasicPower+',')>0 for xml path('')),1,1,'')
from A group by id,UserName,BasicPower
drop table A;
drop table B;
#4
select a.id,a.username,
GROUP_CONCAT(DISTINCT classname ORDER BY b.id asc SEPARATOR ",") as basicpower
from a,b where find_in_set(b.ID,a.basicpower)
group by a.id;
#5
谢谢大家,我还是直接存名字,不存ID了。