PHP MySQL 代码优化

标签 php mysql

是否有任何 MySQL 函数可以优化此代码?子 ID 获取所有父 ID

function get_parents() {

$ids = array();

while($id) :
    $query = "SELECT placement_id FROM referrals WHERE user_id = $id";
    $query = $this->db->query($query);        
    $result = $query->row();  

    if(!isset($result->placement_id)) :
        break;
    elseif(isset($result->placement_id) && $result->placement_id == 2) :
        break;
    endif;

    $id = $result->placement_id;            
    array_push($ids, $id);

    if($result) :
        continue;
    endif;

    break;
endwhile;

return $ids;

}

上面的代码将返回给定 user_id 的所有父 ID,如果没有找到任何内容,这将停止。我发现这段代码太慢而且负载太重。

我的 table

relations table
|   id  |   user_id |   placement_id    |
|   1   |       2   |       NULL        |
|   2   |       3   |       2           |
|   3   |       4   |       2           |
|   4   |       5   |       3           |
|   5   |       6   |       4           |
|   6   |       7   |       3           |
|   7   |       8   |       3           |
|   8   |       9   |       3           |
|   9   |       10  |       6           |
|   10  |       11  |       5           |
|   11  |       12  |       6           |
|   12  |       13  |       4           |
|   13  |       14  |       3           |
|   14  |       15  |       9           |
|   15  |       16  |       10          |

user_id 是子级,父级是placement_id

最佳答案

您可以将代码重写为:

function get_parents() {
$ids = array();

while($id){
    $query = "SELECT placement_id FROM referrals WHERE user_id = $id";
    $query = $this->db->query($query);        
    $result = $query->row();  

    if(isset($result->placement_id) && $result->placement_id !== 2)
    {
        $id = $result->placement_id;            
        array_push($ids, $id);
    }
}
    return $ids;
}

它排除了一些额外的函数调用,例如 continue、break 等。此外,请确保您的 user_id 类型为 INT,并在此列上建立索引。

关于PHP MySQL 代码优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25352887/

相关文章:

php - 使用平面数组获取多维数组值

mysql - 在 JOIN 表上应用 DISTINCT 不起作用

php - 从 Ajax POST 将数组保存到 MySQL 的正确方法

php - 从列中选择唯一值

javascript - 从选择菜单更改更新 HTTP GET 请求

php - 检测 PHP 中数组的更改

mysql - 两个sql查询之间的区别(使用join和不使用join)

mysql - 固定帖子建模 : having pinned flag column inside "posts" table VS having pinned_posts table

mysql - RDS MySQL 数据到平面文件以在另一个 MySQL 中重新加载 - Std CLI 不工作

php - 根据另一个字段计算一个字段的出现次数