SQL父子 - 主父

时间:2017-03-13 03:00:21

标签: sql sql-server tsql hierarchical-data recursive-query

我需要确定一些链接子代码的主父代码,但我不断收到最大递归错误。我还是SQL的新手,所以有人可以帮我解决这个问题。

理想情况下,我希望最终结果看起来像这样:

Ideal Output

Code I我一直在玩这样的:

WITH Hierarchy(Code, Previous_Code, Master_Parent)
AS
(
SELECT CAST(Code AS VARCHAR(MAX)), CAST(Previous_Code AS VARCHAR(MAX)), CAST('' AS VARCHAR(MAX))
    FROM Test AS LastGeneration
    WHERE CAST(Code AS VARCHAR(MAX)) NOT IN (SELECT COALESCE(CAST(Previous_Code AS VARCHAR(MAX)), '0') FROM Test)     
UNION ALL
SELECT CAST(PrevGeneration.Code AS VARCHAR(MAX)), CAST(PrevGeneration.Previous_Code AS VARCHAR(MAX)),
CAST(CASE WHEN Child.Previous = ''
    THEN(CAST(Child.Code AS VARCHAR(MAX)))
    ELSE(Child.Previous + '.' + CAST(Child.Code AS VARCHAR(MAX)))
END AS VARCHAR(MAX))
    FROM Test AS PrevGeneration
    INNER JOIN Hierarchy AS Child ON PrevGeneration.Code = Child.Previous_Code
)
SELECT *
FROM Hierarchy
OPTION(MAXRECURSION 32767)

1 个答案:

答案 0 :(得分:1)

<?php
header('Content-type: application/json');

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "jammer";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    header('HTTP/1.1 500 Bad connection to Database');
    die("The server is down, we couldn't establish the DB connection");
}
else {
    $conn ->set_charset('utf8_general_ci');
    $userName = $_POST['username'];
    $userPassword = $_POST['userPassword'];

    $sql = "SELECT username, firstName, lastName FROM users WHERE username = '$userName' AND password = '$userPassword'";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $response = array('firstName' => $row['firstNameName'], 'lastName' => $row['lastName']);
        }
        echo json_encode($response);
    }
    else {
        header('HTTP/1.1 406 User not found');
        die("Wrong credentials provided!");
    }
}
$conn->close();
?>

返回

enter image description here