2016-03-04 53 views
0

对于食谱应用程序,我有一张储存一般食谱信息和ID的表格。然后,我有几个其他表格表存储相关的数据,如成分,说明,笔记等。目前我正在使用多个简单的SQL语句获取并连接所有这些数据。PHP MySQL:使用一个查询从多个表中获取所有关联的行?

但是我现在需要将整个结果(与一个配方相关的所有内容,通过它的“recipe_id”)放到一个单独的数组中,以便我可以将它作为一个实体进行操作。

我第一次尝试array_merge,但后来开始使用JOIN,但我不确定他们做我喜欢的。这是我需要采取的路线还有其他选择吗?

这里是我当前的代码:

$conn = connDB(); 
    // Get basic recipe data 
    $sql = "SELECT recipe_id, date_created, name, description, author, cooktime, preptime, totaltime, yield, category_id, cuisine_id, image, image_url, url FROM recipes WHERE recipe_id=" . $recipe_id . " LIMIT 1"; 
    $result = $conn->query($sql); 

    // Check that we get a result - ie a valid recipe_id 
    if ($result->num_rows > 0) { 
     $basicrow = $result->fetch_assoc(); 

     // Get ingredients 
     $sql = "SELECT recipe_id, ingredient_id, ingredient, uom_id, ingredient_quant FROM ingredients WHERE recipe_id=" . $recipe_id . ""; 
     $ingredientresult = $conn->query($sql); 
     $ingredientrow = $ingredientresult->fetch_assoc(); 

     // Get Units Of Measurements 
     $sql = "SELECT uom_id, uom_long, uom_short FROM uom"; 
     $uomresult = $conn->query($sql); 

     if ($uomresult->num_rows > 0) { 
      $uomArray = array(); 
      while($uomrow = $uomresult->fetch_assoc()) { 
       $uomArray[$uomrow['uom_id']]["uom_id"] = $uomrow['uom_id']; 
       $uomArray[$uomrow['uom_id']]["uom_long"] = $uomrow['uom_long']; 
       $uomArray[$uomrow['uom_id']]["uom_short"] = $uomrow['uom_short']; 
      } 
     } 

     // Get instructions 
     $sql = "SELECT recipe_id, instruction_id, instruction FROM instructions WHERE recipe_id=" . $recipe_id . ""; 
     $instructionresult = $conn->query($sql); 

     // Get notes 
     $sql = "SELECT recipe_id, date_created, note FROM notes WHERE recipe_id=" . $recipe_id . ""; 
     $notesresult = $conn->query($sql); 

    } else { 
     echo "No such recipe"; // Not a valid recipe_id 
    } 

    $conn->close(); 
+1

你有没有听说过桌子加入我的朋友? – Matt

+0

@Matt问题说“然后开始使用JOIN,但我不确定他们做我喜欢的事情”,显然他有。 – Barmar

+0

'JOIN'确实是这样做的方法。如果他们没有做你喜欢的事,那么你可能做得不对。但是由于您没有显示您尝试过的内容,因此无法帮助您纠正它。 – Barmar

回答

0

您可以创建关联数组键关闭配方ID,那么你可能会通过这些循环,并结合你想要的格式相关的信息。使用连接是在一个数组中获取这些数据的最佳方式。我唯一需要注意的是查询运行需要多长时间。我个人使用过这两种方法,这一切都取决于我想要做什么,以及需要加载的页面需要多长时间。

+0

是的,这是我现在玩弄的想法。以现在的结果集数组(我已经获得了我想要的数据)并循环遍历它们来创建下一步需要的嵌套数组。 – frdrk

+0

不会使用JOIN为这样的查询创建大量重复结果(如上所述)?每个配方可以有许多成分或少数。许多说明或没有,等等。 – frdrk

+0

连接不应创建任何人的记录。它可能会重复数据。即配方的名称。但这应该很容易处理。 –