gpt4 book ai didi

MySQL 统计所有子类别的产品数量

转载 作者:行者123 更新时间:2023-11-29 13:32:50 25 4
gpt4 key购买 nike

我有两张 table ;类别和产品。对于每个类别,我想计算其所有子类别中有多少产品。我已经数过每个类别有多少个了。示例表是:

类别:

ID  ParentID  ProductCount  SubCategoryProducts
1 NULL 0
2 1 2
3 2 1

产品:

ProductID  CategoryID
123 2
124 2
125 3

所以我希望我的函数能够:

ID  ParentID  ProductCount  SubCategoryProducts
1 NULL 0 3
2 1 2 1
3 2 1 0

它只需要作为一个选择查询,不需要更新数据库。

有什么想法吗?

编辑:SQL FIDdle:http://sqlfiddle.com/#!2/1941a/4/0

最佳答案

如果是我,我会创建一个存储过程。另一种选择是使用 PHP 循环执行第一个查询,然后为每个 ID 运行另一个查询 - 但这种逻辑会大大减慢您的页面速度。

这是一个关于存储过程的很好的教程:http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/

基本上,您可以运行我上面提到的与 PHP 相同的循环(但它运行得更快)。该过程存储在数据库中,可以像函数一样调用。结果与查询相同。

根据要求,这里有一个示例过程(或者更确切地说,它使用了两个),在我的实例中,“ags_orgs”的行为方式与您的类别类似,其中有一个parentOrgID。 “getChildOrgs”的行为也有点像一个冗余函数,因为我不知道我必须走多少层(这是为 MSSQL 编写的 - 可能与 mySQL 存在差异)不幸的是,这不计算行数,而是获取数据。我强烈建议您遵循一两个教程,以更好地掌握它的工作原理:

USE [dbname]
GO

/****** Object: StoredProcedure [dbo].[getChildOrgs] Script Date: 09/26/2012 15:30:06 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[getChildOrgs]

@myParentID int,
@isActive tinyint = NULL

AS
BEGIN

SET NOCOUNT ON
DECLARE @orgID int, @orgName varchar(255), @level int

DECLARE cur CURSOR LOCAL FOR SELECT orgID FROM dbo.ags_orgs WHERE parentOrgID = @myParentID AND isActive = ISNULL(@isActive, isActive) ORDER BY orderNum, orgName


OPEN cur
fetch next from cur into @orgID
WHILE @@fetch_status = 0
BEGIN
INSERT INTO #temp_childOrgs SELECT orgID,orgName,description,parentOrgID,adminID,isActive,@@NESTLEVEL-1 AS level FROM dbo.ags_orgs WHERE orgID = @orgID

EXEC getChildOrgs @orgID, @isActive
-- get next result
fetch next from cur into @orgID
END
CLOSE cur
DEALLOCATE cur

END

GO

此过程调用的:

USE [dbname]
GO

/****** Object: StoredProcedure [dbo].[execGetChildOrgs] Script Date: 09/26/2012 15:29:34 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[execGetChildOrgs]

@parentID int,
@isActive tinyint = NULL,
@showParent tinyint = NULL

AS

BEGIN

CREATE TABLE #temp_childOrgs
(
orgID int,
orgName varchar(255),
description text,
parentOrgID int,
adminID int,
isActive tinyint,
level int
)
-- if this isn't AGS top level (0), make the first record reflect the requested organization
IF @parentID != 0 AND @showParent = 1
BEGIN
INSERT INTO #temp_childOrgs SELECT orgID,orgName,description,parentOrgID,adminID,isActive,0 AS level FROM dbo.ags_orgs WHERE orgID = @parentID
END

exec getChildOrgs @parentID, @isActive

SELECT * FROM #temp_childOrgs
DROP TABLE #temp_childOrgs
END

GO

关于MySQL 统计所有子类别的产品数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19167048/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com