当前位置: 代码迷 >> Sql Server >> access查询符合条件的记录(英雄贴:哪位高手是高手?)
  详细解决方案

access查询符合条件的记录(英雄贴:哪位高手是高手?)

热度:78   发布时间:2016-04-24 09:40:50.0
access查询符合条件的记录(英雄贴:谁是高手?)
怎样用sql语言以表2中group字段中“a”为条件查询表1的记录,表3为结果。
 表1
 id  name           zid
 1    王朝           1,2,3,5,6
 2     马汉          2,5,9
 3     张龙         1,6,12,15,18
 4     赵虎         2,6,23,25
 5     奥巴马     3,6,8,15,19
表2
 id    group     zid
 1         a         1
 2         a         3
 3         a         6
 4         a         8
 5         b        12
 6         b         2
 7         b        15
 8         b        19
 9         b        23
表3
 id       name      zid
 1        王朝      1,2,3,5,6
 3        张龙      1,6,12,15,18
 4        赵虎       2,6,23,25
 5        奥巴马    3,6,8,15,19
------解决思路----------------------

create table t1
(id int identity(1,1),
 name varchar(15),
 zid varchar(20)
 )
 
 insert into t1
 select '王朝','1,2,3,5,6'     union all
 select '马汉','2,5,9'         union all
 select '张龙','1,6,12,15,18'  union all
 select '赵虎','2,6,23,25'     union all
 select '奥巴马','3,6,8,15,19' 

create table t2
(id int identity(1,1),
 [group] char(2),
 zid varchar(2)
 )
 
insert into t2
select 'a', '1' union all
select 'a', '3' union all
select 'a', '6' union all
select 'a', '8' union all
select 'b', '12' union all
select 'b' ,'2'  union all
select 'b' ,'15' union all
select 'b' ,'19' union all
select 'b' ,'23'


select t1.id,name,t1.zid from t1
where exists(select * from t2 where [group]='a' and charindex(t2.zid,t1.zid)>0 )

/*
1 王朝 1,2,3,5,6
3 张龙 1,6,12,15,18
4 赵虎 2,6,23,25
5 奥巴马 3,6,8,15,19
*/

------解决思路----------------------
SELECT T1.* FROM 表1 T1
WHERE EXISTS(SELECT 1 FROM 表2 T2 WHERE ','+T1.zid+','LIKE'*,'+CONVERT(VARCHAR(10),T2.zid)+',*'
AND T2.[group]='a')
--在SQL SERVER 里是用%%的,在ACCESS里是用**号的!
--如果在VS2005的TableAdapter里又要用%%,用*不行
  相关解决方案