How to join two tables together with same number of rows by their order

前端 未结 9 1939
庸人自扰
庸人自扰 2020-12-19 04:38

I am using SQL2000 and I would like to join two table together based on their positions

For example consider the following 2 tables:

table1
-------
name
-         


        
相关标签:
9条回答
  • 2020-12-19 05:02

    Do you have anything that guarantees ordering of each table?

    As far ax I know, SQL server does not make any promise on the ordering of a resultset unless the outer query has an order by clause. In your case you need Each table to be ordered in a deterministic manner for this to work.

    Other than that, in SQL 2000, as answered before me, a temp table and two cursors seem like a good answer.

    Update: Someone mentioned inserting both tables into temp tables, and that it would yield better performance. I am no SQL expert so I defer to those who know on that front, and since I had an up-vote I thought you should investigate those performance considerations. But in any case, if you do not have any other information in your tables than what you showed us I'm not sure you can pull it off, ordering-wise.

    0 讨论(0)
  • 2020-12-19 05:06

    If your tables aren't two large, you could create two temp tables in memory and select your content into them in a specific order, and then join them on the row Number.

    e.g.

    CREATE TABLE #Temp_One (
        [RowNum] [int] IDENTITY (1, 1) NOT NULL ,
        [Description] [nvarchar] (50) NOT NULL
    )
    
    CREATE TABLE #Temp_Two (
        [RowNum] [int] IDENTITY (1, 1) NOT NULL ,
        [Description] [nvarchar] (50) NOT NULL
    )
    
    INSERT INTO #Temp_One
    SELECT Your_Column FROM Your_Table_One ORDER BY Whatever
    
    INSERT INTO #Temp_Two
    SELECT Your_Column FROM Your_Table_Two ORDER BY Whatever
    
    SELECT * 
    FROM #Temp_One a 
        LEFT OUTER JOIN #Temp_Two b 
             On a.RowNum = b.RowNum
    
    0 讨论(0)
  • 2020-12-19 05:08

    would be best to use row_number(), but that is only for 2005 and 2008, this should work for 2000...

    Try this:

    create table table1 (name varchar(30))
    insert into table1 (name) values ('cat')
    insert into table1 (name) values ('dog')
    insert into table1 (name) values ('mouse')
    
    create table table2 (cost int)
    insert into table2 (cost) values (23)
    insert into table2 (cost) values (13)
    insert into table2 (cost) values (25)
    
    Select IDENTITY(int,1,1) AS RowNumber
    , Name
    INTO #Temp1
    from table1
    
    
    Select IDENTITY(int,1,1) AS RowNumber
    , Cost
    INTO #Temp2
    from table2
    
    select * from #Temp1
    select * from #Temp2
    
    SELECT
        t1.Name, t2.Cost
        FROM #Temp1                 t1
            LEFT OUTER JOIN #Temp2  t2 ON t1.RowNumber=t2.RowNumber
        ORDER BY t1.RowNumber
    
    0 讨论(0)
提交回复
热议问题