我有两个表,如A和B.每个表都有一个升序列(ID)。 我想加入表LIKE C表。数据不是静态的,但在A和B中,行数始终相等。我尝试过加入声明,但无法找到答案。谢谢你的帮助。
A (ID)
--
2
3
4
6
8
B (ID)
--
11
12
13
14
15
C ( IDA , IDB )
--
2 11
3 12
4 13
6 14
8 15
答案 0 :(得分:3)
如果您正在使用支持row_number()的数据库,例如Oracle,postgresql,sql sql server:
select a_id, b_id
from (select row_number() over(order by id) as a_rn, id as a_id from a) x
join (select row_number() over(order by id) as b_rn, id as b_id from b) y
on x.a_rn = y.b_rn
小提琴: http://sqlfiddle.com/#!15/5ac6b/1/0
如果您正在使用mysql,则可以使用变量模拟row_number:
select a_id, b_id
from (select @rn := @rn + 1 as a_rn, id as a_id
from a
cross join (select @rn := 0) r) x
join (select @rx := @rx + 1 as b_rn, id as b_id
from b
cross join (select @rx := 0) r) y
on x.a_rn = y.b_rn
答案 1 :(得分:1)
试试这个:
select a.id ida,b.id idb from
( select a.*, row_number() over (order by id) rn from a) a
join (select b.*, row_number() over (order by id) rn from b) b on a.rn=b.rn
答案 2 :(得分:0)
联接无关表
演示SQL脚本
IF OBJECT_ID('Tempdb..#T1') IS NOT NULL DROP TABLE #T1;
CREATE TABLE #T1 (T1_Name VARCHAR(75));
INSERT INTO #T1 (T1_Name) VALUES ('Animal'),('Bat'),('Cat'),('Duet');
SELECT * FROM #T1;
IF OBJECT_ID('Tempdb..#T2') IS NOT NULL DROP TABLE #T2;
CREATE TABLE #T2 (T2_Class VARCHAR(10));
INSERT INTO #T2 (T2_Class) VALUES ('Z'),('T'),('H');
SELECT * FROM #T2;
要联接不相关的表,我们将引入一个序列号的通用联接列,如下所示。
SQL脚本
SELECT T1.T1_Name,ISNULL(T2.T2_Class,'') AS T2_Class FROM
( SELECT T1_Name,ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS S_NO FROM #T1) T1
LEFT JOIN
( SELECT T2_Class,ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS S_NO FROM #T2) T2
ON t1.S_NO=T2.S_NO;