注册 登录
编程论坛 SQL Server论坛

这个SQL怎么写?

南川 发布于 2010-12-20 16:06, 606 次点击
我有2张表,第一张表的其中一行数据是   
No     value
1      32,33,34
 
我需要从第二表中查出相应数据
Id      Name
32      aaaaa
33      bbbbb
34      ccccc
4 回复
#2
png2010-12-20 23:16
假定表1的No与表2的Id是同一对象的同一属性, 可以用类似 -

Select TableOne.*, TableTwo.*
From TableOne join TableTwo on TableOne.No = TableTwo.Id
Where TableOne.No = 1
#3
q325956672010-12-20 23:53
支持!
#4
juejitianya2010-12-21 10:41
程序代码:

--模拟数据环境
if exists(select * from sysobjects where name = 't2' and xtype = 'u')
    drop table t1
Go
    create table t1(no int, value varchar(10))
Go
    insert into t1 values(1, '32,33,34')
    insert into t1 values(2, '22,23,24')
Go
    if exists(select * from sysobjects where name = 't2' and xtype = 'u')
        drop table t2
Go
    create table t2(ID int, name varchar(10))
go
    insert into t2
    select 32, 'aaaaaa'
    union
    select 33, 'bbbbbb'
    union
    select 34, 'cccccc'
    union
    select 22, 'dddddd'
    union
    select 23, 'eeeeee'
    union
    select 24, 'ffffff'
   
   
Go

--执行相应的查询操作
    select t1.no, t2.ID, t2.name
    from t1
    inner join t2 on t1.value like '%'+CAST(t2.id as varchar(10))+'%'
   
你看看是否可以满足你的需求。
因为时间原因,这个语句没有对模糊查询条件的严密性进行推敲,供你做个参考!
#5
南川2010-12-22 09:16
select t1.no, t2.ID, t2.name
    from t1
    inner join t2 on  ','+t1.value+',' like '%,'+CAST(t2.id as varchar(10))+',%'
貌似这样更严谨点
1