国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

使用附加條件透過中間表計(jì)算Laravel和Mysql相關(guān)的模型的數(shù)量。
P粉514458863
P粉514458863 2023-07-24 15:47:02
0
1
758
<p>我有一個(gè)MySQL查詢(使用Laravel Eloquent的急切載入和withCount函數(shù)建構(gòu)),在處理大數(shù)據(jù)集時(shí)有一些效能問題,有沒有辦法改進(jìn)下面的查詢? </p><p>我需要取得所有的商店,並計(jì)算與商店相關(guān)的產(chǎn)品數(shù)量(透過中間表關(guān)聯(lián)),但是還有一個(gè)附加條件,即商店的type_id等於產(chǎn)品的type_id。我認(rèn)為這個(gè)第二個(gè)條件導(dǎo)致查詢沒有使用正確的索引。 </p><p>兩個(gè)模型之間有一個(gè)中間表。 </p><p>商店(id,type_id,owner_id)產(chǎn)品(id,type_id)商店產(chǎn)品(shop_id,product_id)</p><p>我在所有外鍵上都有索引,還在shop_product(shop_id,product_id)上有一個(gè)複合索引。 </p><p>所以我的查詢是這樣的:</p><p><br /></p> <pre class="brush:php;toolbar:false;">select shops.*, ( select count (*) from products inner join shop_products on products.id = shop_products.product_id where shops.id = shop_products.shop_id and products.type_id = shops.type_id) from shops where shops.owner_id in (?)</pre> <p>is it possible that this query could be optimized somehow, maybe not using this laravel's withCount whereColumn query?</p> <pre class="brush:php;toolbar:false;">... Shop::withCount(['products' => fn($query) => $query->whereColumn('products. type_id', '=', 'shops.type_id')]);</pre> <p>完整的查詢是這樣的:</p> <pre class="brush:php;toolbar:false;">Shop::whereIn('owner_id', [123]) ->withCount(['products' => fn($query) => $query->whereColumn('products.type_id', '=', 'shops.type_id')]) ->get()</pre> <p>我是否需要在商店(id,type_id)和產(chǎn)品(id,type_id)上新增組合索引? </p>
P粉514458863
P粉514458863

全部回覆(1)
P粉618358260

我沒有測(cè)試過這個(gè),但我會(huì)嘗試類似的東西

Shop::whereIn('owner_id', [123])
            ->withCount(['products' => fn($query) => $query->select(['id','type_id'])->whereColumn('products.type_id', '=', 'shops.type_id')])
            ->get()

所以我剛剛添加了一些欄位(你需要的欄位和應(yīng)用程式需要識(shí)別產(chǎn)品的欄位),但如果只需要計(jì)數(shù),我會(huì)嘗試不使用ID。

我假設(shè)當(dāng)你取得「products」時(shí),它會(huì)拉取所有數(shù)據(jù),如果有像body/description等「text」類型字段,速度會(huì)很慢。

此外,不確定,但你可以嘗試使用'type_id'而不是'products.type_id',因?yàn)槟阋呀?jīng)在'products'關(guān)係中了。還可以檢查優(yōu)化拉取商店的方式。

最新下載
更多>
網(wǎng)站特效
網(wǎng)站源碼
網(wǎng)站素材
前端模板