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

前端 未结 9 1938
庸人自扰
庸人自扰 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 04:53

    This is NOT possible, since there's absolutely no guarantee regarding the order in which the rows will be selected.

    There are a number of ways to achieve what you want (see other answers) provided you're lucky regarding the sorting order, but none will work if you aren't, and you shouldn't rely on such queries.

    Being forced to do this kind of queries strongly smells of a bad database design.

    0 讨论(0)
  • 2020-12-19 04:55

    in 2000 you will either have to run 2 forward only cursors and insert into a temp table. or insert the values into a temp table with an extra identity column and join the 2 temp tables on the identity field

    0 讨论(0)
  • 2020-12-19 04:56

    Absolutely. Use the following query but make sure that (order by) clause uses the same columns the order of rows will change which you dont want.

    select
    (
    row_number() over(order by name) rno, * from Table1
    ) A  
    (
    row_number() over(order by name) rno, * from Table2
    ) B
    JOIN A.rno=B.rno
    

    order by clause can be modified according to user linkings

    The above query produces unique row_numbers for each row, which an be joined with row_numbers of the other table

    0 讨论(0)
  • 2020-12-19 04:56

    Consider using a rank (rownum in Oracle) to dynamically apply ordered unique numbers to each table. Simply join on the rank column and you should have what you need. See this Microsoft article on numbering rows.

    0 讨论(0)
  • 2020-12-19 04:57

    Xynth - built in row numbering is not available until SQL2K5 unfortunately, and the example given by microsoft actually uses triangular joins - a horrific hidden performance hit if the tables get large. My preferred approach would be an insert into a pair of temp tables using the identity function and then join on these, which is basically the same answer already given. I think the two-cursors approach sounds much heavier than it needs to be for this task.

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

    You could alter both tables to have an auto_increment column, then join on that.

    As others have told you, SQL has no intrinsic ordering; a table of rows is a set. Any ordering you get is arbitrary, unless you add an order by clause.

    So yeah, there are ways you can do this, but all of them depend on the accidental ordering being what you hope it is. So do this this once, and don't do it again unless you can come up with a way (auto_increments, natural keys, something) to ensure ordering.

    0 讨论(0)
提交回复
热议问题