嵌套循环实现分类-子分类层级展示及子分类产品数量统计
嘿,我来帮你搞定这个嵌套循环展示分类、子分类和对应产品数的需求!
实现分类-子分类-产品数量的嵌套循环展示
首先得明确三张表的关联逻辑:假设dbo.Category有主键CategoryID和分类名称CategoryName;dbo.SubCategory有主键SubCategoryID、父分类IDParentCategoryID、子分类名称SubCategoryName;dbo.Product通过SubCategoryID关联到子分类表。
方式一:先通过SQL一次性获取结构化数据(推荐,避免N+1查询)
先写个联表查询把所有需要的数据一次性拉取出来,这样代码里只需要分组循环就行,性能会好很多:
SELECT c.CategoryID, c.CategoryName, sc.SubCategoryID, sc.SubCategoryName, COUNT(p.ProductID) AS ProductCount FROM dbo.Category c LEFT JOIN dbo.SubCategory sc ON c.CategoryID = sc.ParentCategoryID LEFT JOIN dbo.Product p ON sc.SubCategoryID = p.SubCategoryID GROUP BY c.CategoryID, c.CategoryName, sc.SubCategoryID, sc.SubCategoryName ORDER BY c.CategoryID, sc.SubCategoryID
然后用C#代码做嵌套循环处理(其他语言逻辑类似):
// 假设已经通过DataReader或ORM拿到查询结果,存在List<CategorySubProduct>集合中 // 先按分类分组 var groupedByCategory = queryResults.GroupBy(r => new { r.CategoryID, r.CategoryName }); foreach (var categoryGroup in groupedByCategory) { // 输出分类名称 Console.Write($"{categoryGroup.Key.CategoryName}"); // 嵌套遍历该分类下的子分类 foreach (var subItem in categoryGroup) { // 输出子分类和对应产品数(无产品时显示0) Console.Write($" --- {subItem.SubCategoryName} ({subItem.ProductCount})"); } // 每个分类结束后换行 Console.WriteLine(); }
方式二:纯嵌套循环查询(符合你要求的嵌套逻辑,但不推荐)
如果一定要在代码层做嵌套查询(先查所有分类,再逐个查子分类,再逐个查产品数),可以这样写(以C# ADO.NET为例):
// 替换成你的数据库连接字符串 string connStr = "Server=.;Database=YourDB;Trusted_Connection=True;"; using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); // 1. 查询所有分类 string getCategoriesSql = "SELECT CategoryID, CategoryName FROM dbo.Category ORDER BY CategoryID"; using (SqlCommand cmd = new SqlCommand(getCategoriesSql, conn)) using (SqlDataReader reader = cmd.ExecuteReader()) { while (reader.Read()) { int categoryId = reader.GetInt32(0); string categoryName = reader.GetString(1); Console.Write($"{categoryName}"); // 2. 嵌套查询当前分类下的子分类 string getSubsSql = "SELECT SubCategoryID, SubCategoryName FROM dbo.SubCategory WHERE ParentCategoryID = @CatID ORDER BY SubCategoryID"; using (SqlCommand subCmd = new SqlCommand(getSubsSql, conn)) { subCmd.Parameters.AddWithValue("@CatID", categoryId); using (SqlDataReader subReader = subCmd.ExecuteReader()) { while (subReader.Read()) { int subId = subReader.GetInt32(0); string subName = subReader.GetString(1); // 3. 嵌套查询当前子分类的产品数量 string countSql = "SELECT COUNT(ProductID) FROM dbo.Product WHERE SubCategoryID = @SubID"; using (SqlCommand countCmd = new SqlCommand(countSql, conn)) { countCmd.Parameters.AddWithValue("@SubID", subId); int productCount = (int)countCmd.ExecuteScalar(); Console.Write($" --- {subName} ({productCount})"); } } } } Console.WriteLine(); } } }
关键提醒
- 性能优先选方式一:方式二会触发大量数据库请求(1次分类查询 + N次子分类查询 + M次产品数查询),数据量大时会明显变慢。
- 处理空数据:如果某个分类没有子分类,方式一会只显示分类名称,方式二则不会输出子分类部分,你可以根据需求加判断调整显示逻辑。
内容的提问来源于stack exchange,提问作者Freddakos
相关产品推荐
相关产品推荐

