简体   繁体   English

查询优化

[英]query optimization

I have a query of the form 我有以下形式的查询

SELECT uid1,uid2 FROM friend WHERE uid1 IN (SELECT uid2 FROM friend WHERE uid1='.$user_id.') and uid2 IN (SELECT uid2 FROM friend WHERE uid1='.$user_id.') SELECT uid1,uid2 from朋友WHERE uid1 IN(SELECT uid2 FROM朋友WHERE uid1 ='。$ user_id。')和uid2 IN(SELECT uid2 FROM朋友WHERE uid1 ='。$ user_id。')

The problem now is that the nested query 现在的问题是嵌套查询

SELECT uid2 FROM friend WHERE uid1='.$user_id.' 从朋友WHERE uid1 ='。$ user_id中选择uid2。

returns a very large number of ids(approx. 5000). 返回大量id(大约5000)。

The table structure of the friend table is uid1(int), uid2(int). 好友表的表结构为uid1(int),uid2(int)。 This table is used to determine whether two users are linked together as friends. 该表用于确定两个用户是否作为朋友链接在一起。

Any workaround? 任何解决方法? Can I write the query in a different way? 我可以用其他方式编写查询吗? Or is there some other way to solve this issue. 还是有其他解决方法。 I'm sure I am not the first person to face such a problem. 我确定我不是第一个遇到这种问题的人。

Any help would be greatly appreciated. 任何帮助将不胜感激。

You can eliminate one subquery by using a single join with an OR statement. 您可以通过对OR语句使用单个联接来消除一个子查询。

However, to eliminate any double rows you would have to return only DISTINCT rows. 但是,要消除任何重复的行,您只需要返回DISTINCT行即可。

SELECT DISTINCT f1.uid1, f1.uid2 
  FROM friend AS f1 INNER JOIN 
    friend AS f2 ON (f1.uid1 = f2.uid2 OR f1.uid2 = f2.udi) 
  WHERE f2.uid1='.$user_id.'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM