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

一个简单的用in做限定的嵌套查询的sql语句,但没有结果
两个表FriendTable 和Activity,想看看朋友发起的活动,使用下面的查询(OrganizerId 发起者的id,在Activity表中;friendId 在FriendTable 表中,其中,记录中myId=1的记录 friendId 字段内容是“2,3 ”)
select * 
from Activity
where OrganizerId in (select friendId from FriendTable where myId=1)
没有查到任何结果(实际有两个)



select * 
from dbo.Activity
where Organizer in (2,3 )
结果:
2 旅游 20 2  
3 出国 100 3  

   
select friendId from FriendTable where myId=1
结果:
2,3

不知道是什么原因

------解决方案--------------------
用exists,不用in ,效率高些.
------解决方案--------------------
这样子是不行的,相当于 where Organizer in ('2,3') 2,3是一个字符串。
------解决方案--------------------
SQL code

select *  
from Activity a
where exists  (select 1 from FriendTable
     where myId=1 and charindex(','+ltrim(a.OrganizerId)+',',','+b.OrganizerId+',') > 0)

------解决方案--------------------
如果select friendId from FriendTable where myId=1
结果:
为2,3
不是2行
2
3
用LZ的查询肯定查不出结果
可用exec语句
declare @str nvarchar(200)
set @str=(select top 1 friendId from FriendTable where myId=1)
if @str is not null
begin
set @str='select * from Activity where OrganizerId in ('+@str+')'
exec (@str)
end