在開發程序中,我們經常遇到一對多的場景,
例如:查詢訂單串列,并且展示訂單詳情商品、數量資料
思路0:傳統做法
- a. 查詢訂單串列
- b. 遍歷訂單詳情
$orderList = select * from order where xx;
foreach($orderList as $orderItem) {
$orderItem->detailList = select * from order_detail where order_id = $orderItem->id;
}
- 分析:查詢SQL次數為:N+1(N為訂單個數),這樣頻繁請求資料庫,影響效率
- 優化:減少頻繁請求資料庫
思路1:
- a. 查詢訂單串列后,利用in查出所有訂單詳情
- b. 通過(訂單表id => 訂單詳情表order_id)遍歷匹配資料
$orderList = select * from order where xx;
$orderId = array_pluck($orderList, 'id'); // Laravel內置陣列輔助函式
$orderDetailList = select * from order_detail where order_id IN $orderId;
foreach($orderList as $orderItem) {
$detailListTemp = [];
foreach($orderDetailList as $orderDetailItem) {
if ($orderItem->id == $orderDetailItem->order_id) {
$detailListTemp[] = $orderDetailItem;
}
}
$orderItem->detailList = $detailListTemp;
}
- 分析:降低查詢后,但2層遍歷,復雜度較高,數量過大容易記憶體溢位
- 優化:降低復雜度
思路2:
- a. 查詢訂單串列后,利用in查出所有訂單詳情
- b. 訂單詳情串列轉換成以訂單ID為索引,用isset來匹配訂單的詳情
$orderList = select * from order where xx;
$orderId = array_pluck($orderList, 'id'); // Laravel內置陣列輔助函式
$orderDetailList = select * from order_detail where order_id IN $orderId;
// 將訂單詳情轉換成以訂單ID為索引【方式1】
$orderDetailList = arrayGroup($orderDetailList, 'order_id');
// 或:將訂單詳情轉換成以訂單ID為索引【方式2:如果為一對一,可以用array_column】
// $orderList = array_column($orderDetailList, null, 'order_id');
foreach($orderList as $orderItem) {
$orderItem->detailList = $orderDetailList[$orderItem->id] ?? [];
}
// 根據KEY陣列分組
function arrayGroup($list, $key) {
$newList = [];
foreach ($list as $item) {
$newList[$item[$key]][] = $item;
}
return $newList;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/257169.html
標籤:其他
上一篇:SQL練習28:查找描述資訊中包括robot的電影對應的分類名稱以及電影數目
下一篇:問一個oracle行列轉換問題
