簡體   English   中英

PHP MySQL多個SQL查詢或每個查詢的JOIN

[英]PHP MySQL Multiple SQL Queries or JOIN for each query

如果我有兩個帶有各自列的表:

=====================
product_categories
=====================
id | name
=====================

=======================
products
=======================
id | category_id | name
=======================

而且我有以下PHP函數:

// Returns an array of all rows from the products
function getProducts() { ... } 

// returns the corresponding row to the given id of the product category
function getProductCategory($category_id) { ... } 

目前,我在帶有以下標題的表格中顯示所有產品的列表:

  • ID
  • 類別
  • 名稱

其中category是與產品的category_id對應的category_id名稱。

目前,我正在使用foreach循環來迭代產品,並為每個產品調用getProductCategory(...)函數:

<?php
...

$products = getProducts();

foreach ($products as $product) {
    $product_category = getProductCategory($product['category_id']);
    ...
}

...
?>

如果有很多產品具有很多重復的查詢,那將是對數據庫的大量查詢。

如果getProducts()函數在SQ L語句中使用JOIN包含所有類別信息,這將是一個好習慣嗎?

如果要每次獲取idcategory_nameproduct_name ,則應使用ONE方法,並避免進行一次select ,然后對每種產品進行一次foreach ,而對另一項進行select以獲取所有價值。

所以嘗試這樣的事情也許:

function getProductsData() {

    $querie = 'SELECT 
                 p.id, p.name,
                 pc.name as Category
               FROM products as p
               LEFT JOIN product_categories as pc on pc.id = p.category_id
               ORDER BY p.name; -- optionnal
              ';

    // Get the data and return them
    // You should get an array with one row = 
    // id (of the product) / name (of the product) / Category (the name of the category)


}

是的,加入會更好。 它將減少獲取類別的查詢數量。 否則,您可以單獨查詢以獲取如下代碼所示的類別,但我建議您加入。

$products = getProducts();
$categoryIds = [];
foreach ($products as $product) {
    $categoryIds[] = $product['category_id'];
    ...
}
$product_category = getProductCategory($categoryIds);

您必須在getProductCategory()修改查詢,並where in條件中添加where in以便比較類別ID在getProductCategory() ,可以內嵌類別ID,以將其添加到where in子句中。

暫無
暫無

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

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