表一
===================
id name
-------------------
1 m
2 m
3 a
4 u
5 g
表二
===================
id name
-------------------
8 m
9 m
10 u
11 a
12 x
15 m
预期结果
===================
1 m 8
2 m 9
3 a 11
4 u 10
我需要通过名称在表2中找到与表1相关联的id。但表2中的ID必须不同。
如果我加入,我会收到错误的交叉点:
select t1.id as i1, t1.name, t2.id as i2 from t1
join t2 on t1.name = t2.name
i1 name i2
--------------------
'1','m','8'
'2','m','8'
'1','m','9'
'2','m','9'
'4','u','10'
'3','a','11'
'1','m','15'
'2','m','15'
我需要这个用于来自不同系统的表同步。
答案 0 :(得分:2)
您可以使用以下查询:
SELECT t1.id, t1.name, t2.id
FROM (
SELECT id, name,
@rn1 := IF(@n = name, @rn1 + 1,
IF(@n := name, 1, 1)) AS rn1
FROM Table1
CROSS JOIN (SELECT @rn1 := 0, @n := '') AS vars
ORDER BY name, id) AS t1
INNER JOIN (
SELECT id, name,
@rn2 := IF(@n = name, @rn2 + 1,
IF(@n := name, 1, 1)) AS rn2
FROM Table2
CROSS JOIN (SELECT @rn2 := 0, @n := '') AS vars
ORDER BY name, id
) AS t2 ON t1.name = t2.name AND t1.rn1 = t2.rn2
ORDER BY t1.id
查询使用变量来模拟ROW_NUMBER()
窗口函数,目前在MySQL中不可用。变量@rn1
,@rn2
枚举属于相同 name
分区的记录,其顺序由id
字段确定。