PHP MySQL代码优化

时间:2014-08-17 19:30:10

标签: 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,如果找不到任何内容,则会停止。我发现这段代码太慢而且负载很重。

我的表

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

2 个答案:

答案 0 :(得分:0)

您可以将代码重写为:

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等。另外,Make sure you have INT as type of user_id with indexing on this column.

答案 1 :(得分:0)

我个人会这样做:

<?php

define('MAX_NEST_DEPTH', 15);

function get_parent($child_id) {

  $child_id = (int) $child_id;
  $parents = array();
  $counter = 0;

  do {
    $sql = "SELECT placement_id
      FROM referrals
      WHERE user_id = {$child_id}";
    $query = $this->db->query($query);
    $result = $query->row();

    $child_id = (int) $result->placement_id;
    $parent[] = $child_id;

    $counter++;
  }
  while ($child_id !=  0 || $counter == MAX_NEST_DEPTH);

  return $parents;
}

你不会在循环中绕过查询,mysql不支持n级嵌套SELECT,否则我们可以一次性完成。