[英]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) { ... }
目前,我在帶有以下標題的表格中顯示所有產品的列表:
其中category是與產品的category_id對應的category_id
名稱。
目前,我正在使用foreach循環來迭代產品,並為每個產品調用getProductCategory(...)
函數:
<?php
...
$products = getProducts();
foreach ($products as $product) {
$product_category = getProductCategory($product['category_id']);
...
}
...
?>
如果有很多產品具有很多重復的查詢,那將是對數據庫的大量查詢。
如果getProducts()
函數在SQ
L語句中使用JOIN
包含所有類別信息,這將是一個好習慣嗎?
如果要每次獲取id
, category_name
和product_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.