34,837
社区成员




'需求内容:'
假设现在有两个表,一个是表T1,一个表T2
录入的数据如下:
T1
id name
---------------------------
1 wang;huang;yan
2 li;cai;tang
3 zhang;chen
4 song;gao
T2
name property
---------------------------
wang 上海;北京
li 深圳
zhang 广州
song 厦门;唐山;西安
T1中的name列及T2中的property不能再拆分,如何构造语句来实现通过查询T2表中的property中的广州来得到T1表中id的值?
use test
go
if object_id('test.dbo.t1') is not null drop table t1
-- 创建数据表
create table t1
(
id int,
name char(20)
)
go
--插入测试数据
insert into t1 select 1,'wang;huang;yan'
union all select 2,'li;cai;tang'
union all select 3,'zhang;chen'
union all select 4,'song;gao'
go
if object_id('test.dbo.t2') is not null drop table t2
-- 创建数据表
create table t2
(
name char(10),
property char(20)
)
go
--插入测试数据
insert into t2 select 'wang','上海;北京'
union all select 'li','深圳'
union all select 'zhang','广州'
union all select 'song','厦门;唐山;西安'
union all select 'li','广州;深圳'
go
--代码实现
'解法一'
select * from t1 t where
exists(select 1 from t2
where charindex(';'+name+';',';'+t.name+';')>0 and [property] like '%广州%')
'解法二'
select t1.* from t1 , t2
where charindex(';'+t2.name + ';',';'+t1.name+';') > 0 and charindex(';广州;',';'+t2.property+';') > 0
order by t1.id
charindex(';'+name+';',';'+t.name+';')>0 这样的写法能实现么??
好像 charindex 函数里的第一个表达式必须是定值,不应该包含字段变量吧...
郁闷...
'两表的 name 为 varchar ,porperty 为 char 时'
第一种解法可以得出想要的结果:
id name
------------------------
2 li;cai;tang
3 zhang;chen
而第二种解法却是这样的结果:
id name
-------------------------
2 li;cai;tang
'当表中的所有字符型字段均为 varchar 时'
两种解法均能够得到相同的结果!!
均为:
id name
------------------------
2 li;cai;tang
3 zhang;chen
'这是什么原因啊????'
SELECT * FROM t1 t
WHERE
exists
(SELECT name from t2 where property like '%广州%' and CHARINDEX(rtrim(ltrim(name)),t.name)>0)
if object_id('dbo.t1') is not null drop table t1
-- 创建数据表
create table t1
(
id int,
name varchar(20)
)
go
--插入测试数据
insert into t1 select 1,'wang;huang;yan'
union all select 2,'li;cai;tang'
union all select 3,'zhang;chen'
union all select 4,'song;gao'
go
if object_id('dbo.t2') is not null drop table t2
-- 创建数据表
create table t2
(
name varchar(10),
property varchar(20)
)
go
--插入测试数据
insert into t2 select 'wang','上海;北京'
union all select 'li','深圳'
union all select 'zhang','广州'
union all select 'song','厦门;唐山;西安'
union all select 'li','广州;深圳'
go
--代码实现
--'解法一'
select * from t1 t where
exists(select 1 from t2
where charindex(';'+name+';',';'+t.name+';')>0 and [property] like '%广州%')
/*
(4 行受影响)
(5 行受影响)
id name
----------- --------------------
2 li;cai;tang
3 zhang;chen
(2 行受影响)
*/
SELECT * FROM t1
WHERE CHARINDEX(RTRIM(LTRIM((SELECT top 1 name from t2 where property='广州'))),name)>0