2016-09-15 62 views
0

如果我從JOIN查詢中獲取結果,如何爲每個連接中的每個表獲取單獨的變量?如何在連接中將每一個MySQL表分割成單獨的變量

例如:

$result = $mysql->query(sprintf('SELECT * 
    FROM `TableOne` one 
    JOIN `TableTwo` two ON (one.TwoID = two.TwoID) 
    JOIN `TableThree` three ON (one.ThreeID = three.ThreeID) 
    WHERE one.OneID = %u', 
    (int)$primary_key)); 
while ($row = $result->fetch_assoc()) { 
    // Instead of $row, I want: 
    // $one: all fields from TableOne 
    // $other: all fields from TableTwo and TableThree 
} 

回答

0

解決方案:

function mysqli_fetch_assoc_per_table(mysqli_result $result, $instruction) { 
    $row = $result->fetch_assoc(); 
    if (!$row) return false; 
    $fields = $result->fetch_fields(); 

    $groups = array(); 
    foreach (explode(',', $instruction) as $arg) { 

     $group = array(); 
     foreach (explode('|', $arg) as $table) { 
      foreach ($fields as $field) { 
       if ($field->table == $table) { 
        $group[$field->name] = $row[$field->name]; 
       } 
      } 
     } 

     $groups[] = $group; 
    } 

    return $groups; 
} 

用法:

while (list($one, $other) = mysqli_fetch_assoc_per_table($result, 'one,two|three')) { 

} 
+0

這可以在一個循環中沒有做過3 – nogad

相關問題