我现在有表a 表b
表b中有字段 col,内容是这样的 23,25,53,56,28 这里的值是对应表a中的id值我想根据表b中col字段的内容查询表a中想对应的id所有信息select * from a where id in (select col from b)这样写只返回一条记录,是id=23的记录,怎么才能返回全部记录?我用的数据库是mysql5.0
表b中有字段 col,内容是这样的 23,25,53,56,28 这里的值是对应表a中的id值我想根据表b中col字段的内容查询表a中想对应的id所有信息select * from a where id in (select col from b)这样写只返回一条记录,是id=23的记录,怎么才能返回全部记录?我用的数据库是mysql5.0
--mysql不会
select a.* from a
inner join b on a.id=b.col
去mysql版吧
declare @table table (id int,col varchar(1))
insert into @table
select 101,'a' union all
select 201,'b' union all
select 301,'c' union all
select 409,'d'declare @userid varchar(2000),
@sqlstr varchar(4000)
set @userid='201,102,301,104,199'SELECT * FROM @table
WHERE CHARINDEX(','+CAST(id AS VARCHAR(4))+',',','+@userid+',')>0
/*
id col
----------- ----
201 b
301 c
*/
嗯,在 mysql 中找一个类似 charindex 的函数写一下就可以了
参考一下
这里我还要说明一下: not in 和 not exists 在有null的情况下结果不同。declare @小组表 table (小组编码 int,小组名称 varchar(1))
insert into @小组表
select 1,'a' union all
select 2,'b' union all
select 3,'c' union all
select 4,'d' union all
select 5,'e' union all
select null,null union all
select 7,'g' union all
select 8,'h' union all
select 9,'i' union all
select 10,'j'declare @登记表 table (小组 int)
insert into @登记表
select null union all
select 3 union all
select 4 union all
select 5 union all
select 6SELECT 小组编码,小组名称
FROM @小组表 a where
not exists (select * from @登记表 b where b.小组=a.小组编码)/*
小组编码 小组名称
----------- ----
2 b
7 g
8 h
9 i
10 j
*/SELECT 小组编码,小组名称
FROM @小组表 where 小组编码 not in (select 小组 from @登记表)
/*
小组编码 小组名称
----------- ----(0 row(s) affected)
*/
select col from b
结果为 col=“23,25,53,56,28”
在查询a表
select * from a where id in (23,25,53,56,28)
这样应该是返回5条记录但是这样写
select * from a where id in (select col from b)
只返回一条记录,就是id=23的一条