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

后端 未结 3 1691
轻奢々
轻奢々 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 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
    

提交回复
热议问题