对于大量in参数,比如下面的,还有not in如何优化呢?我缩减了in 里面的参数,实际里面有更多的参数:
select * FROM [dbo].[UserFriend] AS [Extent1]
LEFT OUTER JOIN [dbo].[User] AS [Extent2] ON [Extent1].[friend_thUserId] = [Extent2].[id]
WHERE ([Extent1].[userId] IN (5445,87411,2373,1194,3209,51023,3101,312354,278412)) AND
( NOT ([Extent1].[friend_thUserId] IN (5445,87411,2373,1194,3209,51023,3101,312354,278412) )) AND
([Extent1].[friend_thUserId] <> @p__linq__0)
新建了个临时表,插入数据进去,不考虑插入临时表的时间,然后作join, 反而更慢了, 而且结果也不对,先帮忙看看如何改写成exists 格式,另外看看如何优化? friend_thUserId,id,userId都有index
create table #tmp_friend ( userId int)
insert into #tmp_friend select 5445 union all select 87411。。。
SELECT *
FROM [dbo].[UserFriend] AS [Extent1]
LEFT OUTER JOIN [dbo].[User] AS [Extent2] ON [Extent1].[friend_thUserId] = [Extent2].[id]
WHERE not exists ( select 1 from #tmp_friend t where [Extent1].friend_thUserId = t.userid)
and exists ( select 1 from #tmp_friend t where [Extent1].userId = t.userid)
AND
([Extent1].[friend_thUserId] <> @p__linq__0)
------解决方案--------------------
两种方式的结果不对,是因为在存在null值的情况下not in 和 not exists 的筛选出来的结果不一样,not in(非null值)的结果不带null,
not exists的结果包含null值
------解决方案--------------------
改成这样试试:
create table #tmp_friend ( userId int)
insert into #tmp_friend select 5445 union all select 87411。。。
SELECT *
FROM [dbo].[UserFriend] AS [Extent1]
LEFT hash OUTER JOIN [dbo].[User] AS [Extent2]
ON [Extent1].[friend_thUserId] = [Extent2].[id]
WHERE
not exists ( select 1 from #tmp_friend t where [Extent1].friend_thUserId = t.userid)
and exists ( select 1 from #tmp_friend t where [Extent1].userId = t.userid)
AND
([Extent1].[friend_thUserId] <> @p__linq__0)
------解决方案--------------------
你的瓶颈是键值查找,这是*号导致的。所以问你是不是非要用*