簡體   English   中英

從多個表中獲取數據的最佳方式

[英]Best way to get data from multiple tables

在此處輸入圖片說明

我想從上面的 3 個表中獲取數據並存儲在這樣的數組中。

在此處輸入圖片說明

只能一個查詢加入多個表並返回我需要的數組嗎?

或者我為每個表編寫查詢然后組合 3 個數組? (獲取表A中的所有ID,查找表B和C中ID匹配的值)?

哪個更有效?

如果可能,請編寫示例代碼。 謝謝你。

試試下面的查詢

SELECT a.item,a.item_desc,b.meta_value,c.name
   FROM TableA a 
   JOIN TableB b ON a.id = b.id 
   JOIN tableC c ON c.id = b.id
   ORDER BY a.item_desc

$data = array(); // create a variable to hold the information
while (($row = mysql_fetch_array($result, MYSQL_ASSOC)) !== false){
$data[] = $row; // add the row in to the results (data) array
}

print_r($data); // print result

1 個 mysql 查詢比 3 個更快(即使有連接)

一個 mysql 查詢可以從所有三個表中收集數據,如另一個答案所示。 並且只執行一個查詢而不是三個單獨的查詢會更快。

聯接產生數據的排列

當您連接多個表時,Mysql 將返回多行,每個數據排列一個。 這意味着某些數據(如項目 ID)將在多行上重復。 鑒於表 A 在表 B 上有許多條目,而表 A 在表 C 上也有許多條目,結果集將是這樣的:

| A1 | B1 | C1 |
| A1 | B1 | C2 |
| A1 | B2 | C1 |
| A1 | B2 | C2 |

將 mysql 輸出轉換為所需的數據結構

以下代碼完成了這項工作。 你可能想以某種方式改進它。

<?php
// Connect to the mysql server
$mysqli = new mysqli('localhost', $env['username'], $env['password'], $env['database']);
if ($mysqli->connect_errno) {
    echo 'Failed to connect';
}

echo $mysqli->host_info . "\n";

// SQL query to join 3 tables based on item ID.
// This will return one row for each permutation of data.
// Note that the column 'desc' in the OPs question has been replaced with 'description'
// to avoid a naming conflict with a MYSQL keyword.
$res = $mysqli->query("select distinct a.id, a.item, a.description, b.metakey, b.metavalue, c.name from a join b on a.id = b.item_id join c on a.id = c.item_id order by a.item"); 
print_r($res);

// Transform the mysql output which contains duplicate information
// into the desired data structure as specified in the OPs question.
$output = [];
while($row = $res->fetch_assoc()) {
        // We need to use the row ID (Item ID) to process the mysql rows.

       // Only add the full row if the Item ID has not previously been added.                                                   
        if (!isset($output[$row['id']])) {
            // Form the desired data structure
            $output[$row['id']] = [
                "DATA" => [
                    // The data array is an indexed array.
                    $row['item'],
                    $row['description'],
                ],
                "META" => [
                    // The meta array is an associative array and uses key value pairs.
                    $row['metakey'] => $row['metavalue'],
                ],
                // The extra array is an indexed array.
                "EXTRA" => [  
                    $row['name'],
                ],
            ]; 
        } 
        // Here we fill in the missing data from the partially duplicated mysql rows.
        // We drill down into the output array to check which keys have been added already,
        // and if it hasn't been added we add it.
        if (!isset($output[$row['id']]['META'][$row['metakey']])){
            $output[$row['id']]['META'][$row['metakey']] = $row['metavalue'];
        }
        // Same again, but a slightly different check. This time we are dealing with
        // an indexed array so we need to see if the value has been added.
        if (!in_array($row['name'], $output[$row['id']]['EXTRA'])) {
            $output[$row['id']]['EXTRA'][] = $row['name'];
        }
}

print_r($output);

上面的代碼已經過測試。 您只需要添加您自己的 $env 數組,並為您的 mysql 服務器添加適當的 mysql 連接詳細信息。

參考

1

暫無
暫無

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

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