Search code examples
mysqlsqljoinrow-number

MySQL join on row number (first with first, second with second etc)


Let's say I have 2 simple tables

Table t1    Table t2
+------+    +------+
| i    |    | j    |
+------+    +------+
|   42 |    |    a |
|    1 |    |    b |
|    5 |    |    c |
+------+    +------+

How can I have an output of the 2 tables, joined without any condition except the row number?

I would like to avoid the creation of another index if possible.

I am using MySQL 5.7


With this example, the output would be :

Table output
+------+------+
| i    | j    |
+------+------+
|   42 |    a |
|    1 |    b |
|    5 |    c |
+------+------+

Solution

  • What you ask can be done, assuming that your comment is true;

    "Even if table i and j are subqueries (containing order by)?"

    Schema (MySQL v5.7)

    CREATE TABLE table_1 ( i INT );
    CREATE TABLE table_2 ( j VARCHAR(4) );
    
    INSERT INTO table_1
    VALUES (3),(5),(1);
    
    INSERT INTO table_2
    VALUES ('c'), ('b'),('a');
    

    Query

    SELECT t1.i, t2.j
    FROM (SELECT t1.i
               , @rownum1 := @rownum1 + 1 AS rownum
          FROM (SELECT table_1.i
                FROM table_1
                ORDER BY ?) t1
                   CROSS JOIN (SELECT @rownum1 := 0) v) t1
             JOIN (SELECT t2.j
                        , @rownum2 := @rownum2 + 1 AS rownum
                   FROM (SELECT table_2.j
                         FROM table_2
                         ORDER BY ?) t2
                            CROSS JOIN (SELECT @rownum2 := 0) v) t2 ON t2.rownum = t1.rownum;
    

    However, this approach is a) not efficient, and b) indicative of questionable design. You probably want to look for something that actually relates your two tables or, if nothing exists, create something. If there is really nothing that relates the two tables, then you'll have trouble with the ORDER BY clauses anyway.