您的位置:程序门 -> ms-sql server -> 应用实例



求助,帮忙写个sql语句


[收藏此页] [打印本页]选择字色:背景色:字体:[][][]


求助,帮忙写个sql语句[已结贴,结贴人:pengteling]
发表于:2008-02-18 15:25:17 楼主
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=张三)
我上面的语句会报错,求高手帮忙解决,谢谢了
发表于:2008-02-18 15:26:431楼 得分:0
charindex
发表于:2008-02-18 15:26:502楼 得分:5
sql code
tba id classid name 1 1,2,3 西服 2 23 中山装 3 13 名裤 tbb id classname 1 衣服 2 上衣 3 裤子 我得的结果是 id classname name 1 衣服,上衣,裤子 西服 2 上衣,裤子 中山装 3 衣服,裤子 名裤 create table tba(id int,classid varchar20),name varchar10)) insert into tba values1,'1,2,3','西服') insert into tba values2,'2,3' ,'中山装') insert into tba values3,'1,3' ,'名裤') create table tbb(id varchar10), classname varchar10)) insert into tbb values'1','衣服') insert into tbb values'2','上衣') insert into tbb values'3','裤子') go --第1种方法,创建函数来显示 create function f_hb(@id varchar10)) returns varchar1000) as begin declare @str varchar1000) set @str='' select @str=@str+','+[classname] from tbb where charindex','+cast(id as varchar)+',',','+@id+',')>0 return stuff@str,1,1,'') end go select id,classid=dbo.f_hb(classid),name from tba drop function f_hb /* id classid name ----------- ------------- ---------- 1 衣服,上衣,裤子 西服 2 上衣,裤子 中山装 3 衣服,裤子 名裤 (所影响的行数为 3 行) */ --第2种方法.update whileexistsselect * from tba,tbb where charindex(tbb.id,tba.classid) >0)) update tba set classid= replace(classid,tbb.id,tbb.classname) from tbb where charindex(tbb.id,tba.classid)>0 select * from tba /* id classid name ----------- -------------------- ---------- 1 衣服,上衣,裤子 西服 2 上衣,裤子 中山装 3 衣服,裤子 名裤 (所影响的行数为 3 行) */ drop table tba,tbb
发表于:2008-02-18 15:28:053楼 得分:2
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
发表于:2008-02-18 15:28:524楼 得分:0
'张三'
发表于:2008-02-18 15:29:175楼 得分:10
sql code
select t1.* from a t1 ,b t2 where charindex','+id+',',','t2.id_a+',')>0 and t2.name=张三
发表于:2008-02-18 15:29:316楼 得分:3
sql code
declare @a table (id varchar10),name varchar10)) insert into @a select '101','语文' insert into @a select '103','数学' insert into @a select '201','英语' declare @b table (name varchar10),id_a varchar50)) 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='张三'


id name name id_a
101 语文 张三 101,103
103 数学 张三 101,103

发表于:2008-02-18 15:30:167楼 得分:0
sql code
select t1.* from a t1 ,b t2 where charindex','+t1.id+',',','+t2.id_a+',')>0 and t2.name='张三'
发表于:2008-02-18 15:57:438楼 得分:0
非常感谢,fa_ge   的答案比较简洁,谢谢大家了,分值比较少,大家笑纳了


快速检索

最新资讯
热门点击