哪个更快,SUB-Query 或 IN-Query?
Which one is Faster, SUB-Query or IN-Query?
如果我想 select whether i am following
thread
与否。
我有两种方法...但我不知道哪一种在性能和速度方面更好。谁能帮帮我?
方法一
$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
*/
}
方法二
$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");
一次往返胜过两次。这是因为将 SQL 发送到服务器、让它解析它、执行它并将结果发回时会产生一些开销。在一次往返中完成所有事情(通常)更好。
如果我想 select whether i am following
thread
与否。
我有两种方法...但我不知道哪一种在性能和速度方面更好。谁能帮帮我?
方法一
$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
*/
}
方法二
$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");
一次往返胜过两次。这是因为将 SQL 发送到服务器、让它解析它、执行它并将结果发回时会产生一些开销。在一次往返中完成所有事情(通常)更好。