Group All Related Records in Many to Many Relationship, SQL graph connected components

后端 未结 6 882
遥遥无期
遥遥无期 2020-12-08 21:48

Hopefully I\'m missing a simple solution to this.

I have two tables. One contains a list of companies. The second contains a list of publishers. The mapping between

6条回答
  •  爱一瞬间的悲伤
    2020-12-08 22:36

    You are trying to find all of the connected components of your graph, which can only be done iteratively. If you know the maximum width of any connected component (i.e. the maximum number of links you will have to take from one company/publisher to another), you could in principle do it something like this:

    SELECT
        MIN(x2.groupID) AS groupID,
        x1.Company,
        x1.Publisher
    FROM Table1 AS x1
        INNER JOIN (
            SELECT
                MIN(x2.Company) AS groupID,
                x1.Company,
                x1.Publisher
            FROM Table1 AS x1
                INNER JOIN Table1 AS x2
                ON x1.Publisher = x2.Publisher
            GROUP BY
                x1.Publisher,
                x1.Company
        ) AS x2
        ON x1.Company = x2.Company
    GROUP BY
        x1.Publisher,
        x1.Company;
    

    You have to keep nesting the subquery (alternating joins on Company and Publisher, and with the deepest subquery saying MIN(Company) rather than MIN(groupID)) to the maximum iteration depth.

    I don't really recommend this, though; it would be cleaner to do this outside of SQL.

    Disclaimer: I don't know anything about SQL Server 2012 (or any other version); it may have some kind of additional scripting ability to let you do this iteration dynamically.

提交回复
热议问题