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

求助,帮忙写个sql语句
A表 
ID name others
101 语文 ....
103 数学 ...
201 英语 ....
...
B表
name ID_A
张三 101,103
李四 103,201

现在要写一个查询,
B表中某一记录查出对应的A表其它记录

select * from A where ID in (select ID_A from B where name=张三)
我上面的语句会报错,求高手帮忙解决,谢谢了

------解决方案--------------------
SQL code
tba
ID  classid   name
1     1,2,3   西服 
2     2,3    中山装
3     1,3    名裤


tbb 
id   classname
1     衣服
2     上衣
3     裤子

我得的结果是
id   classname            name
1     衣服,上衣,裤子      西服 
2          上衣,裤子     中山装
3     衣服,裤子          名裤

create table tba(ID int,classid varchar(20),name varchar(10))
insert into tba values(1,'1,2,3','西服')
insert into tba values(2,'2,3'  ,'中山装')
insert into tba values(3,'1,3'  ,'名裤')
create table tbb(ID varchar(10), classname varchar(10))
insert into tbb values('1','衣服')
insert into tbb values('2','上衣')
insert into tbb values('3','裤子')
go

--第1种方法,创建函数来显示
create function f_hb(@id varchar(10))
returns varchar(1000)
as
begin
  declare @str varchar(1000)
  set from #t
insert into #t select * from #t2
drop table #t2
end
go
select id_no,convert(char,in_date,120) as in_date from #t a;
drop table #t,a;

------解决方案--------------------
ID name others 
101 语文 .... 
103 数学 ... 
201 英语 .... 
... 
B表 
name ID_A 
张三 101,103 
李四 103,201 

SQL code
select A.* from A,B where charindex(a.id,b.ID_A)>0

------解决方案--------------------
SQL code

select   t1.*   from   A  t1 ,B t2
where   charindex(','+ID+',',','t2.ID_A+',')>0 and  t2.name=张三

------解决方案--------------------
SQL code
declare @a table (id varchar(10),name varchar(10))
insert into @a select '101','语文'
insert into @a select '103','数学'
insert into @a select '201','英语'

declare @b table (name varchar(10),id_a varchar(50))
insert into @b select '张三','101,103'
insert into @b select '李四','103,201'

select * from @a a,@b b
where charindex(a.id,b.id_a)>0
and b.name='张三'