什么更快?使用通配符和OR进行SQL查询,还是使用php循环进行catch-all查询进行过滤?

Wor*_*ing 1 php mysql sql loops wildcard

我在一张桌子上运行查询.我需要最终结果是一个行数组,其中当前用户被列为数据库行记录的消息中的参与者.两个参与者列是staff和clients,并且包含用户ID和/或角色名称的序列化数组(例如,a:3:{i:0;s:8:"staffman";i:1;s:3:"203";i:2;s:3:"170";}).

尝试在SQL查询中过滤掉当前用户的所有非匹配项,或者执行全部查询(可能在几百行上),然后循环遍历它们以过滤掉那些用户不是参与者?

SQL选项:

$query = "SELECT * FROM ".self::$messages;
if($is_client) $query .= " WHERE type = 'clients'";
elseif($is_staff) $query .= " WHERE type = 'staff' AND (staff LIKE '%\"".$user->ID."\"%' OR staff LIKE 'staff\"%')";
elseif(!$is_admin)
{
    $query .= " WHERE type = 'staff' AND (staff LIKE '%\"".$user->ID."\"%' OR staff LIKE 'staff\"%' OR staff LIKE 'clientman%'";
    if($is_staffman) $query .= " OR staff LIKE 'staffman%'";
    if($is_accountant) $query .= " OR staff like 'accountant%'";
    $query .= ")";
}
$query .= " ORDER BY updated DESC";
Run Code Online (Sandbox Code Playgroud)

LOOP选项:

$col = $is_client ? 'clients' : 'staff';
$query = "SELECT * FROM ".self::$messages." WHERE type = {$col} ORDER BY updated DESC";
// do the query, then check if there are results. if results...     
foreach($results as $msg)
{
    if(empty($msg->$col)) continue;
    $users = unserialize($msg->$col);
    if($is_client)
    {
        if(!in_array($user->ID, $users) && !in_array('client', $users)) continue;   
    }
    elseif(!$is_admin && $msg->created_by != $user->ID)
    {
        if(!in_array($user->ID, $users))
        {
            if(!in_array('staff', $users))
            {
                if(!$is_clientman || !in_array('clientman', $users))
                {
                    if(!$is_staffman || !in_array('staffman', $users))
                    {
                        if(!$is_accountant || !in_array('accountant', $users)) continue;
                    }
                }
            }
        }
    }
    // match found, do stuff with it here
}
Run Code Online (Sandbox Code Playgroud)

Pra*_*tik 7

在这种情况下,您应该始终使用SQL选项.

$query = "SELECT * FROM ".self::$messages;
if($is_client) $query .= " WHERE type = 'clients'";
elseif($is_staff) $query .= " WHERE type = 'staff' AND (staff LIKE '%\"".$user->ID."\"%' OR staff LIKE 'staff\"%')";
elseif(!$is_admin)
{
    $query .= " WHERE type = 'staff' AND (staff LIKE '%\"".$user->ID."\"%' OR staff LIKE 'staff\"%' OR staff LIKE 'clientman%'";
    if($is_staffman) $query .= " OR staff LIKE 'staffman%'";
    if($is_accountant) $query .= " OR staff like 'accountant%'";
    $query .= ")";
}
$query .= " ORDER BY updated DESC";
Run Code Online (Sandbox Code Playgroud)

为什么?

1.通过过滤WHERE子句,看你已经获得了更少的记录(只需要那些记录).获取所有记录并在php中过滤它是没有意义的.

2.看到它在PHP中管理代码很麻烦,因为它很复杂.

3.Less no.of lines.

4.它大多数时候都是由SQL管理的,php逻辑会使它变慢.