哪一个更快,SUB查询或IN查询?

时间:2015-02-11 13:28:23

标签: mysql sql performance join subquery

如果我想选择whether i am following thread,请选择<{1}}。

我有两种方法可以这样做......但我不知道哪种方法在性能和速度方面会更好。任何人都可以帮助我吗?

方法1

$cui = $_SESSION['user_id'];

$data  = mysqli_query($con,"
SELECT t.*,( select count(follow_id) from follows where object_id = 
t.thread_id AND object_type='thread' AND user_id = $cui) as me_follow FROM threads t
");
  while($row = mysqli_fetch_assoc($data)){
       /*
           $row['me_follow'] = 0 if i aint following
           $row['me_follow'] = 1 if  i am following  
       */
   }

方法2

$cui = $_SESSION['user_id'];

  $data = mysqli_query($con,"SELECT * FROM threads");
  $ids = array();
  while($row = mysqli_fetch_assoc($data)){
       $ids[] = $row['thread_id'];
   }
$ids = join($ids,",");
$data = mysqli_query($con,"SELECT COUNT(*) FROM follows WHERE object_id IN($ids) AND user_id = $cui");

1 个答案:

答案 0 :(得分:1)

一次往返胜过两次。这是因为将SQL发送到服务器,让它解析它,执行它并发回结果会有一些开销。在一次往返中做所有事情(通常)更好。