两个表各有一个属性的每个值都是集合,现在想用sql找出这两个集合相同的元素,并在结果中将这个集合中的元素单个的组成一个新的属性,同时找出所对应的其他属性
我现在把我的问题简化为表格:
表一:able (两个属性 tv ,id)
Tv id
w;r;h 1
e 2
t 3
k 4
m;n 5
表二 per (两个属性lg,anti)
lg anti
W;e;r;t Dan
W;h Chu
W;h;e Yuan
n the
现在我想实现这样一个结果,不知道sql可不可以实现
id tv'' anti
1 w dan
1 w chu
1 w yuan
1 r dan
1 h chu
1 h yuan
2 e dan
2 e yuan
3 t dan
5 n the
各位大侠帮帮忙!帮忙写一下sql 语句。不胜感激!
我现在把我的问题简化为表格:
表一:able (两个属性 tv ,id)
Tv id
w;r;h 1
e 2
t 3
k 4
m;n 5
表二 per (两个属性lg,anti)
lg anti
W;e;r;t Dan
W;h Chu
W;h;e Yuan
n the
现在我想实现这样一个结果,不知道sql可不可以实现
id tv'' anti
1 w dan
1 w chu
1 w yuan
1 r dan
1 h chu
1 h yuan
2 e dan
2 e yuan
3 t dan
5 n the
各位大侠帮帮忙!帮忙写一下sql 语句。不胜感激!
if object_id('[able]') is not null drop table [able]
go
create table [able]([Tv] varchar(5),[id] int)
insert [able]
select 'w;r;h',1 union all
select 'e',2 union all
select 't',3 union all
select 'k',4 union all
select 'm;n',5
go
if object_id('[per]') is not null drop table [per]
go
create table [per]([lg] varchar(7),[anti] varchar(4))
insert [per]
select 'W;e;r;t','Dan' union all
select 'W;h','Chu' union all
select 'W;h;e','Yuan' union all
select 'n','the'
goselect a.id,a.tv,b.anti
from
(
select
a.id,tv=substring(a.tv,b.number,charindex(';',a.tv+';',b.number)-b.number)
from
able a,master..spt_values b
where
b.type='P'
and
charindex(';',';'+a.tv,b.number)=b.number
) a
join per b on charindex(a.tv,b.lg)>0--测试结果:
/*
id tv anti
----------- ----- ----
1 w Dan
1 w Chu
1 w Yuan
1 r Dan
1 h Chu
1 h Yuan
2 e Dan
2 e Yuan
3 t Dan
5 n the(所影响的行数为 10 行)*/
select a.id,a.tv,b.anti
from
(
select
a.id,tv=substring(a.tv,b.number,charindex(';',a.tv+';',b.number)-b.number)
from
able a,master..spt_values b
where
b.type='P'
and
charindex(';',';'+a.tv,b.number)=b.number
) a
join per b on charindex(a.tv,b.lg)>0
这一段注释一下呢?不是非常理解这些语句的意思。
如果这里的w r .....这些字母各代表的是字符串,那么要做怎么的修改才可以用?(我自己修改了下,但是达不到效果)
例如这样的:
表一able:
tv id
Unigene105830_All Unigene128818_All Unigene144322_All Unigene149389_All Unigene80342_All 1
Unigene92558_All Unigene92863_All Unigene94013_All Unigene94110_All Unigene94300_All 2表二per:
anti lg
anatomical structure Unigene80342_All;Unigene94110_All51_All;Unigene30484_All;Unigene42367_All
biological adhesion Unigene92863_All;Unigene94013_Allene757_All;Unigene82501_All
biological regulation Unigene80342_All;Unigene94110_All51_All;Unigene30484_All;Unigene42367_All
cell killing Unigene144322_All;Unigene92863_All;;Unigene126713_All;Unigene129271_All
cellular component Unigene92558_All;Unigene94110_All;Unigene122021_All;Unigene43091_All得到类似于上面的结果。当然真实的lg和tv的每个值都包含很多个元素,甚至上千个。在得到上述结果的同时,可不可以也得到id,anti同时相同的行数。现在的sql只学了点皮毛,这样的问题真的让我措手不及,由于时间问题就不得不先得到结果再在空余时间深入学习。 请多指教!麻烦了