How do I get every permutation in two totally unrelated tables with t-sql

后端 未结 3 1689
轻奢々
轻奢々 2021-01-14 12:13

I have two tables that are indirectly related by another table

TableA - ID, SomeFieldA

TableB - ID, SomeFieldB

TableAB - IDA, IDB, SomeFiel

相关标签:
3条回答
  • 2021-01-14 12:44
     INSERT TableAB
     SELECT A.ID 'IDA', B.ID 'IDB'
          , A.SomeFieldA+" "+B.SomeFieldB  'SomeFieldAB' 
     FROM A, B
    

    A join without any conditions does all the permutations

    0 讨论(0)
  • 2021-01-14 12:57

    You can do this:

    select
        a.*, b.*
    from
        a, b
    

    This will do a cross join which will give you all possible combinations.

    From there, it's simple to use that within the context of an INSERT statement to populate your AB table.

    0 讨论(0)
  • 2021-01-14 13:06

    Don't use the ancient join syntax: FROM A, B, use a proper join:

    DECLARE @TableA table (Col1 varchar(5), Col2 varchar(5))
    DECLARE @Tableb table (Col1 varchar(5), Col2 varchar(5))
    
    INSERT INTO @TableA VALUES ('a','a')
    INSERT INTO @TableA VALUES ('aa','aa')
    
    INSERT INTO @TableB VALUES ('b','b')
    INSERT INTO @TableB VALUES ('BB','BB')
    
    SELECT
        *
        FROM @TableA
            CROSS JOIN @TableB
        ORDER BY 1
    

    OUTPUT

    Col1  Col2  Col1  Col2
    ----- ----- ----- -----
    a     a     b     b
    a     a     BB    BB
    aa    aa    b     b
    aa    aa    BB    BB
    
    (4 row(s) affected)
    

    this will also produce the same result set:

    SELECT
        *
        FROM @TableA
            JOIN @TableB ON 1=1
        ORDER BY 1
    
    0 讨论(0)
提交回复
热议问题