sql >> データベース >  >> RDS >> Oracle

SQL-フィールド間の関連付けの作成(推移的な関係)

    ORACLEについては何も言えませんが、SQLサーバーの再帰CTEで管理できます。これが私のサンプルソリューションです。テーブルウィッチが1つのテーブルからそれ自体に多対多の関係をマップしていると仮定してあなたが求めたことを実行します

    DECLARE @testData table (EntityID int, EntityName varchar(1))
    DECLARE @EntityRelations table (EntityID1 int, EntityID2 int)
    
    INSERT INTO @testData
    SELECT 1, 'A'
    UNION
    SELECT 2, 'B'
    UNION
    SELECT 3, 'C'
    UNION
    SELECT 4, 'D'
    UNION
    SELECT 5, 'E'
    UNION
    SELECT 6, 'F'
    UNION
    SELECT 7, 'G'
    UNION
    SELECT 8, 'Y'
    UNION
    SELECT 9, 'Z'
    
    INSERT INTO @EntityRelations
    SELECT 1, 2
    UNION
    SELECT 9, 2
    UNION
    SELECT 8, 2
    UNION
    SELECT 2, 3
    UNION
    SELECT 2, 4
    UNION
    SELECT 4, 5
    UNION
    SELECT 6, 7;
    
    
    WITH Affiliations (EntityID, Entity1Name, Entity2Name) AS
    (
        SELECT r.EntityID1
              ,e.EntityName as Entity1Name
              ,e2.EntityName as Entity2Name
        FROM @EntityRelations r
            JOIN @testData e ON e.EntityID = r.EntityID1
            JOIN @testData e2 ON e2.EntityID = r.EntityID2
    
        UNION ALL
    
        SELECT r.EntityID1
              ,e.EntityName as Entity1Name
              ,e2.EntityName as Entity2Name
        FROM @EntityRelations r
            JOIN @testData e ON e.EntityID = r.EntityID1
            JOIN @testData e2 ON e2.EntityID = r.EntityID2
            JOIN Affiliations a ON a.EntityID = r.EntityID2
    )
    
    ,AffiliationsReverse (EntityID, Entity1Name, Entity2Name) AS
    (
        SELECT r.EntityID2
              ,e.EntityName as Entity1Name
              ,e2.EntityName as Entity2Name
        FROM @EntityRelations r
            JOIN @testData e ON e.EntityID = r.EntityID1
            JOIN @testData e2 ON e2.EntityID = r.EntityID2
    
        UNION ALL
    
        SELECT r.EntityID2
              ,e.EntityName as Entity1Name
              ,e2.EntityName as Entity2Name
        FROM @EntityRelations r
            JOIN @testData e ON e.EntityID = r.EntityID1
            JOIN @testData e2 ON e2.EntityID = r.EntityID2
            JOIN AffiliationsReverse a ON a.EntityID = r.EntityID1
    )
    
    
    SELECT DISTINCT EntityName
    FROM
    (
    SELECT a.Entity1Name AS EntityName
    FROM Affiliations a
        JOIN AffiliationsReverse ar ON ar.EntityID = a.EntityID
    
    UNION
    
    SELECT a.Entity2Name AS EntityName
    FROM Affiliations a
        JOIN AffiliationsReverse ar ON ar.EntityID = a.EntityID
    
    UNION
    
    SELECT ar.Entity1Name AS EntityName
    FROM Affiliations a
        JOIN AffiliationsReverse ar ON ar.EntityID = a.EntityID
    
    UNION
    
    SELECT ar.Entity2Name AS EntityName
    FROM Affiliations a
        JOIN AffiliationsReverse ar ON ar.EntityID = a.EntityID
    
    
    ) s
    



    1. データベース内の各テーブルにmysqlクエリを適用します

    2. SQLServerで階層関係をグループ化する方法

    3. 正しいSQLのヘルプが必要

    4. KubernetesのMySQLに別のユーザーを追加する