+ -
当前位置:首页 → 问答吧 → 问一个简单的查询语句

问一个简单的查询语句

时间:2011-12-01

来源:互联网

表A
id , userids
1 1,2
2 4
3 19

表B
useid info
1 xxx
2 xxx
3 xxx

怎么读出 表B 在表A的 userids 字段中的记录
例如 当A.id =1 时候读出 B.id =1, B.id=2 的记录

我开始想 select * from b where userid in ( select userids from A where A.id=1 )
发现不行

以前弄过 太久忘记了 


作者: ayun00   发布时间: 2011-12-01

SQL code
select a.* from a inner join b on charindex(','+ltrim(b.userid)+',',','+a.userids+',')>0

作者: qianjin036a   发布时间: 2011-12-01

or:
SQL code
select a.* from a inner join b on ','+a.userids+',' like '%,'+ltrim(b.userid)+',%'

作者: qianjin036a   发布时间: 2011-12-01

SQL code

if object_id('A','U') is not null
   drop table A
go
create table A
(
 id int,
 userids varchar(10)
)
go
insert into A
select 1,'1,2' union all
select 2,'4' union all
select 3,'19'
go
if object_id('B','U') is not null
   drop table B
go
create table B
(
 userid int,
 info varchar(10)
)
go
insert into B
select 1,'xxx' union all
select 2,'xxx' union all
select 3,'xxx'
go
select * from B where charindex(','+ltrim(userid)+',',(select ','+userids+',' from A where id=1))>0
go
/*
userid      info
----------- ----------
1           xxx
2           xxx

(2 行受影响)
*/

作者: pengxuan   发布时间: 2011-12-01

不拼sql 语句 能达到效果吗

作者: ayun00   发布时间: 2011-12-01

引用 4 楼 ayun00 的回复:

不拼sql 语句 能达到效果吗


上面写的好像都不是拼sql语句的.

加逗号是为了防止出错,如 5 可以从 15 中找到,但 ,5, 就不能从 ,15, 中找到了.

作者: qianjin036a   发布时间: 2011-12-01