簡體   English   中英

有沒有更好的方法使用 PHP 對同一個表運行多個 SQL 查詢?

[英]Is there a better way to run multiple SQL queries to the same table using PHP?

我有一個查詢,它請求一個 ID(PK)和一個訂單號,並將它們放入一個數組中。 然后我遍歷數組中返回的數據並運行另外兩個查詢以查找訂單號在數據庫中出現的次數並獲取屬於該訂單號的發票號。 我在這個設置中看到的問題是返回編譯的數據數組需要一段時間(大約 9 秒)。 有沒有更快的方法來獲得我正在尋找的返回結果?

我試圖在網上找到一些文章並遇到了mysqli_multi_query 這是進行多個查詢以收集我想要獲取的數據類型的更好途徑嗎?

<?php
    require 'config.php';
    $sql = "SELECT id,internal_order_number FROM orders GROUP BY internal_order_number ORDER BY created_date desc LIMIT 0 ,50";
    $query=mysqli_query($mysqli, $sql);
    if (!$query) {
        throw new Exception(mysqli_error($mysqli)."[ $sql]");
    }
    $data = array();
    while( $row=mysqli_fetch_array($query) ) {  // preparing an array
      $nestedData=array();
      $nestedData['line_id'] = $row["id"];
      $nestedData['internal_order_number'] = $row["internal_order_number"];
      $data[] = $nestedData;
    }
    $compiled_data = array();

    // Loop through data array with additional queries
    foreach($data as $line){
      $new_data = array();

      // Get item counts
      $item_counts = array();
      $get_count = " SELECT internal_order_number FROM orders WHERE internal_order_number = '".$line['internal_order_number']."' ";
      $count_query=mysqli_query($mysqli, $get_count);
      while ($counts=mysqli_fetch_array($count_query)){
        if (isset($item_counts[$counts['internal_order_number']])) {
          $item_counts[$counts['internal_order_number']]++;
        } else {
          $item_counts[$counts['internal_order_number']] = 1;
        }
      }
      $product_count = $item_counts[$line['internal_order_number']];

      // Get invoice numbers
      $invoice_array = array();
      $get_invoices = " SELECT invoice_number FROM orders WHERE internal_order_number = '".$line['internal_order_number']."'";
      $invoice_query=mysqli_query($mysqli, $get_invoices);
      while ($invoice=mysqli_fetch_array($invoice_query)){
        if(!in_array($invoice['invoice_number'], $invoice_array)){
          $invoice_array[] = $invoice['invoice_number'];
        }
      }
      $invoices = implode(", ",$invoice_array);

      $new_data['order_number'] = $line['internal_order_number'];
      $new_data['count'] = $product_count;
      $new_data['invoices'] = $invoices;
      $compiled_data[] = $new_data;
    }
    mysqli_close($mysqli);
    print_r($compiled_data);
?>

什么,為什么你基本上做同樣的查詢 3 次。 你第一個選擇它們,你的第二個查詢需要同一個表,確保第一個表訂單號 == 表訂單號,最后一個只是獲取發票號......?

只需做一個查詢:

SELECT internal_order_number, invoice_number FROM table WHERE ...

然后循環遍歷它並執行您需要的操作。 你不需要3個查詢...

暫無
暫無

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

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