簡體   English   中英

PHP MySQL:使用一個查詢從多個表中獲取所有關聯的行?

[英]PHP MySQL: Fetching all associated rows from multiple tables using one query?

對於食譜應用程序,我有一個表,用於存儲常規食譜信息和ID。 然后,我得到了其他幾個表,這些表存儲了相關的數據,例如成分,說明,說明等。 目前,我正在使用多個簡單的SQL語句獲取並連接所有這些數據。

但是,我現在需要將整個結果(與一個配方有關的所有內容,通過其“ 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();

您可以創建以配方ID為鍵的關聯數組,然后可以遍歷它們並以所需的形式組合信息。 使用聯接是在一個數組中獲取此數據的最佳方法。 我唯一需要注意的是查詢運行需要多長時間。 我親自使用了這兩種方法,這完全取決於我要執行的操作以及有問題的頁面加載所需的時間。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM