这是我的user_relationship表,类似一个人的好友表
现在我要走的是查出一个uid下面的所有uid_the_other然后在uid_the_other的基础上查出所有数据,这张表数据有50W条左右,虽然不算多,但是我写的sql是这样的
SELECT * from user_relationship where uid_the_other in (SELECT uid_the_other from user_relationship where uid='xiaoyp2011')uid_the_other 和uid都建立了索引,但是速度不是一般的慢,,,慢得不得了
实在不知道该咋办,求前辈们帮帮忙
show index from ...以供分析
where exists(select 1 from user_relationship as b where a.uid_the_other=b.uid_the_other and uid='xiaoyp2011')
1)区分表a,b
2)使用exists
3)查看执行计划
show index from ..
SELECT * from user_relationship where uid in (SELECT uid_the_other from user_relationship where uid='xiaoyp2011');
如果是的话,建个联合索引uid,uid_the_other
明确需要查询的列,如只需要COL1,COL2,COL3,可创建组合覆盖索引:
create index idx_uid_uidTheOther_include_col1col2col3 on user_relationship (uid,uid_the_other) include(col1,col2,col3)
明确需要查询的列,如只需要COL1,COL2,COL3,可创建组合覆盖索引:
create index idx_uid_uidTheOther_include_col1col2col3 on user_relationship (uid,uid_the_other) include(col1,col2,col3)
来一个更爆炸点的:
select col1,col2,col3 from user_relationship as a
cross apply (select * from user_relationship as b
where a.uid_the_other=b.uid_the_other and b.uid='xiaoyp2011') as d
where uid_the_other in
(SELECT uid_the_other from user_relationship where uid='xiaoyp2011')与B语句:SELECT * from user_relationship where uid='xiaoyp2011' 区别:B语句查询出的结果与A语句查询出的结果一致:因为:
1、通过B查询出所有结果中的所有uid_the_other在数据库中存在;再根据这些值再回查数据库这不是费两遍功夫吗?
2、楼主需求理解错误!
就是uid_the_other对应多个uid;
也就是针对一个用户的uid。查询出他下面的所有好友uid;然后根据好友的uid反推出好友uid下的好友;那;楼主的语句就是此类的需求sql;用in操作;不管你索引优化多好;随着数据亮的增加;效率一定会越来越坏!