假设我有两个简单的表
Table t1 Table t2
+------+ +------+
| i | | j |
+------+ +------+
| 42 | | a |
| 1 | | b |
| 5 | | c |
+------+ +------+
我如何才能得到两个表的输出,除了行号之外没有任何条件连接?
如果可能的话,我希望避免创建另一个索引。
我使用的是MySQL 5.7
在这个例子中,输出将是:
Table output
+------+------+
| i | j |
+------+------+
| 42 | a |
| 1 | b |
| 5 | c |
+------+------+
假设您的评论是真的,您所问的可以完成;
"即使表i和j是子查询(包含排序依据(?">
架构(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 all
和group 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;
注意:每列中的结果都是按任意和不确定的顺序排列的。查询的不同运行顺序可能有所不同。
您没有提供足够的信息来确保订购。
您可以尝试此代码
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