如果是我,我会创建一个存储过程。另一种选择是通过第一个查询循环使用 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