sql - 想要获取每个类别的产品数量和随机产品图片。下面的查询工作正常,但性能很慢
问题描述
下面的查询获取类别 ID、标题、产品数量和随机产品图片。我想修改以下查询以提高其性能。下面的查询需要 420 毫秒才能执行。
SELECT category_ID,
category_Name,
ISNULL((SELECT TOP 1
product_image1
FROM tbl_products
WHERE product_image1 <> ''
AND product_isActive = 1
AND product_ID IN (SELECT refPrdCat_prdID
FROM tbl_refPrdCatLink
WHERE refPrdCat_catID = category_ID)
ORDER BY NEWID()),
'') AS Product_Image,
ISNULL((SELECT COUNT(1)
FROM tbl_products
WHERE product_isActive = 1
AND product_ID IN (SELECT refPrdCat_prdID
FROM tbl_refPrdCatLink
WHERE refPrdCat_catID = category_ID)),
'') AS countPrd
FROM tbl_category;
解决方案
我发现 product_image1 <> '' 没有必要,因为你在外面使用 isnull,我也看到你在里面使用相同的查询,这就是我使用 cte 的原因。不确定它是否需要一些更改,尝试运行它,请通知我!
with cte_table (ref) as (
select refPrdCat_prdID from tbl_refPrdCatLink where refPrdCat_catID =category_ID
)
select
category_ID,category_Name,
isnull(
select top 1 product_image1 from tbl_products where product_isActive=1 and product_ID in (select * from cte_table) order by newID() ,'') Product_Image,
isnull(
select count(1) from tbl_products where product_isActive=1 and product_ID in (select * from cte_table) order by newID() ,'') countPrd
)
from tbl_category
推荐阅读
- c++ - 最大数据包数
- wordpress - 替换 Wordpress 标题
- elasticsearch - 比较 Kibana 地图中两个字段的平均值
- javascript - 这个反应组件中的这个调用堆栈有问题吗?
- c++ - 两个模板模板参数,一个需要另一个
- c - 通过在 C 中的引用传递来修改函数内部的字符串
- ios - 为什么 Xcode 13 不惜一切代价忽略设备方向设置?
- bootstrap-5 - 如何重置bootstrap 5 text-muted的效果
- powershell - 如何在 Powershell 中实现二进制哈希字符串的 Base64 URL 安全编码?
- r - 如何在 R 中按日期合并/堆叠观察结果