每次循环运行时如何避免执行查询? (优化代码)

时间:2014-07-29 00:58:05

标签: php mysql sql optimization

$query = $db->query("SELECT * 
                     FROM users 
                     ORDER BY username ASC");
while($user = $query->fetch_object()) {
$if_inside = $db->query("SELECT member_id 
                         FROM project_members 
                         WHERE member_id='$user->id' 
                         UNION 
                         SELECT admin_id 
                         FROM project_admins 
                         WHERE admin_id='$user->id'")->num_rows;
if($if_inside < 1) { // if not already in project 
?> 
<option value="<?php echo $user->username; ?>"> 
               <?php echo $user->username; ?> </option>
 <?php
 } 
 }
 ?>

我如何优化上面的代码?如果我的数据库中有100个用户,那么它将查询100次,而且它已经很慢(我有2个用户)

有没有更好的方法来检查用户是否已经在项目中?

1 个答案:

答案 0 :(得分:2)

我认为这是你正在寻找的东西:

$sql = $db->query("Select distinct username from users where username not in (select member_id from project_members union select admin_id from project_admins) order by username ASC");
$queryResult = $sql->fetch_all();

foreach($queryResult as $username) {
    echo "<option value='" . $username . "'>" .  $username . "</option>";
}

针对不在project_members或project_admins中的所有用户名对数据库执行单击,然后对要显示的结果进行预测。