现在我有三个表:
表1:
pre_common_member_profile:
uid(用户的uid),
gender(性别),
birthyear(出生的年),
birthmonth(出生的月),
birthday(出生的日)
表2:
pre_home_friend:
uid(用户的uid),
fuid(加为好友的uid)
表3:
pre_home_friend_request:
fuid(发送好友请求的人),
uid(发送给谁)
要求:
查找表1,但是排除一定条件。
查询表1上面的五个字段,条件为uid=570并且uid不能等于(这两个条件:1、表2中uid=570的fuid的值。2、表3中的fuid=570的uid值。)
请尽量写出的语句效率高一点。
@bdmh
select gender,uid,birthmonth,birthday,birthyear from pre_common_member_profile as p where destination = '济南' and p.uid <> 570 and p.uid < 570 and gender = 0 and uid not in(select fuid from pre_home_friend where uid=570 union select uid from pre_home_friend_request where fuid = 570) order by uid desc
怎么优化一下??
select A.id,B.id,C.id from A inner join B on A.id=B.id inner join C on C.id=A.id
select * from 表1 t1 where t1.uid = 570
and uid not in
(select fuid from 表2 where uid = 570
union
select uid from 表3 where fuid = 570);
你的uid=570并且uid不能等于这两个条件直接是什么关系呢?
直接select gender,uid,birthmonth,birthday,birthyear from pre_common_member_profile as p where destination = '济南' and p.uid < 570 and gender = 0 order by uid desc
uid not in(select fuid from pre_home_friend where uid=570 union select uid from pre_home_friend_request where fuid = 570) 这个没必要,这个始终取得的是空
uid<>570 ,你uid<570 了,还会等于570吗?
这个SQL不难写,给你分析下SQL的优化
pre_home_friend 的 uid字段建立索引
pre_home_friend_request 的 fuid建立索引
pre_common_member_profile 的uid是主键的话,应该是有索引的。修改UID的索引的排序方式为 desc ,默认是ASC的,你可以看下
使用NOT EXISTS 替换not in;
然后看SQL的执行计划。看索引有没有生效
select A.id,B.id,C.id from A inner join B on A.id=B.id inner join C on C.id=A.id
select A from B
sellect *