MySQL 加入行号(第一个与第一个,第二个与第二个等)

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

假设我有 2 个简单的表格

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

我怎样才能得到 2 个表的输出,除了行号之外没有任何条件连接?

我想尽可能避免创建另一个索引。

我正在使用 MySQL 5.7


对于这个例子,输出将是:

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

你可以试试这个代码

select t1.i,t2.j
from
    (SELECT i,@row_num:=@row_num+1 as row_num FROM t1, (SELECT @row_num:= 0) AS sl) t1
join
    (SELECT j,@row_num:=@row_num+1 as row_num FROM t2, (SELECT @row_num:= 0) AS sl) t2
on  t1.row_num=t2.row_num

假设您的评论是真实的,您的要求可以完成;

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

架构 (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');

查询

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;

但是,这种方法 a) 效率不高,并且 b) 表明设计有问题。您可能想要查找与您的两个表实际相关的内容,或者如果不存在,则创建一些内容。如果这两个表真的没有任何关联,那么您无论如何都会遇到 ORDER BY 子句的问题。

如果表的行数不一定相同,则使用 union allgroup by -- 以及变量:

select max(t.i) as i, max(t.j) as j
from ((select (@rn1 := @rn1 + 1) as seqnum, t1.i
       from t1 cross join
            (select @rn1 := 0) params
      ) union all
      (select (@rn2 := @rn2 + 1) as seqnum, t2.j
       from t2 cross join
            (select @rn2 := 0) params
      ) 
     ) t
group by seqnum;

注:每列结果按任意不确定顺序排列。该顺序可能因查询的不同运行而异。

您没有提供足够的信息来确保订购。