我总是有这个问题:
如何在SQL(MySQL)中选择此项:
T1
A
3
4
5
6
7
T2
B
45
63
75
82
95
Result
3-45
4-63
5-75
6-82
7-95
如您所见,该想法是将两个表以相同顺序关联。我尝试过:
SELECT T1.A, T2.B FROM
(SELECT * FROM T1 ORDER BY A DESC) T1,
(SELECT * FROM T2 ORDER BY B DESC) T2
GROUP BY T1.A DESC
我得到:
3-45
4-45
5-45
6-45
7-45
没有成功。
答案 0 :(得分:2)
DROP TABLE IF EXISTS T1;
CREATE TABLE t1
(A INT NOT NULL PRIMARY KEY);
INSERT INTO t1 VALUES
(3),
(4),
(5),
(6),
(7);
DROP TABLE IF EXISTS T2;
CREATE TABLE t2
(B INT NOT NULL PRIMARY KEY);
INSERT INTO t2 VALUES
(45),(63),(75),(82),(95);
SELECT x.a
, y.b
FROM
( SELECT a, @i:=@i+1 i FROM t1, (SELECT @i:=0) vars ORDER BY a) x
JOIN
( SELECT b, @j:=@j+1 j FROM t2, (SELECT @j:=0) vars ORDER BY b) y
ON y.j = x.i;
+---+----+
| a | b |
+---+----+
| 3 | 45 |
| 4 | 63 |
| 5 | 75 |
| 6 | 82 |
| 7 | 95 |
+---+----+
答案 1 :(得分:0)
尝试创建用于连接键的虚拟row_number
Math my = new Math();
答案 2 :(得分:0)
尝试这个短一点的
SET @rowid1 = 0;
SET @rowid2 = 0;
CREATE TEMPORARY TABLE IF NOT EXISTS t1x(INDEX(rowid)) AS (SELECT @rowid1:=@rowid1 + 1 AS rowid, a FROM t1 ORDER BY a);
CREATE TEMPORARY TABLE IF NOT EXISTS t2x(INDEX(rowid)) AS (SELECT @rowid2:=@rowid2 + 1 AS rowid, b FROM t2 ORDER BY b);
SELECT a, b FROM t1x JOIN t2x ON t2x.rowid = t1x.rowid ORDER BY a;