我怎样才能将其转换为mysql查询

时间:2014-12-11 08:17:36

标签: php mysql database

如何将以下内容转换为this kind of MySQL query?我尝试在MySQL编辑器中运行它,但看起来MySQL的语法不同。

-- Working Example
;WITH CTECompany
AS
(
    SELECT 
        EmpID, 
        ParentID, 
        PersonName , 
        0 AS HLevel,
        CAST(RIGHT(REPLICATE('_',5) +  CONVERT(VARCHAR(20),EmpID),20) AS VARCHAR(MAX)) AS OrderByField
    FROM @Company
    WHERE ParentID IS NULL

    UNION ALL

    SELECT 
        C.EmpID, 
        C.ParentID, 
        C.PersonName , 
        (CTE.HLevel + 1) AS HLevel,
        CTE.OrderByField + CAST(RIGHT(REPLICATE('_',5) +  CONVERT(VARCHAR(20),C.EmpID),20) AS VARCHAR(MAX)) AS OrderByField
    FROM @Company C
    INNER JOIN CTECompany CTE ON CTE.EmpID = C.ParentID
    WHERE C.ParentID IS NOT NULL
)

-- Working Example
SELECT 
    EmpID
    , ParentID
    , HLevel
    , PersonName
    , (REPLICATE( '----' , HLevel ) + PersonName) AS Person
FROM CTECompany
ORDER BY OrderByField,PersonName;

1 个答案:

答案 0 :(得分:0)

MySQL没有WITH。只需将该查询移动到子查询中,替换查询第二部分中的CTECompany

SELECT 
    EmpID
    , ParentID
    , HLevel
    , PersonName
    , (REPLICATE( '----' , HLevel ) + PersonName) AS Person
FROM (
        SELECT 
            EmpID, 
            ParentID, 
            PersonName , 
            0 AS HLevel,
            CAST(RIGHT(REPLICATE('_',5) +  CONVERT(VARCHAR(20),EmpID),20) AS VARCHAR(MAX)) AS OrderByField
        FROM Company
        WHERE ParentID IS NULL

        UNION ALL

        SELECT 
            C.EmpID, 
            C.ParentID, 
            C.PersonName , 
            (CTE.HLevel + 1) AS HLevel,
            CTE.OrderByField + CAST(RIGHT(REPLICATE('_',5) +  CONVERT(VARCHAR(20),C.EmpID),20) AS VARCHAR(MAX)) AS OrderByField
        FROM Company C
        INNER JOIN CTECompany CTE ON CTE.EmpID = C.ParentID
        WHERE C.ParentID IS NOT NULL
    )
ORDER BY OrderByField,PersonName;

MySQL也不允许将变量用作表名,因此我将@Company更改为Company