我有两张表如下
T1:
id code field1 field2
1 1000 a1111 a2222
2 2000 b1111 b2222
3 1000 a3333 a4444
4 2000 b3333 b4444
5 2000 b5555 b6666
6 3000 c1111 c2222
7 3000 c3333 c4444
8 3000 c5555 c6666
T2:
t2id t1_code var1
1 1000 xxxx
2 2000 yyyyy
3 3000 zzz
4 3000 mmm
我希望结果表为:
code field1 field2 t1_code var1
1000 a3333 a4444 1000 xxxx
1000 a1111 a2222 null null
2000 b3333 b4444 2000 yyyyy
2000 b5555 b6666 null null
2000 b1111 b2222 null null
3000 c1111 c2222 3000 mmm
3000 c3333 c4444 3000 zzz
3000 c3333 c4444 null null
我试过了:
SELECT t1.code, t1.field1, t1.field2, t2.t1_code, t2.var1
FROM t2, t1
WHERE t1_code = code
ORDER BY code
没有给我答案。
请帮忙......
答案 0 :(得分:0)
好的,你希望连接转到t1中的“第一个”匹配行(其中“first”表示最低id)。
这几乎是一种方法:
SELECT t1.code, t1.field1, t1.field2, t2.t1_code, t2.var1
FROM t1 left outer join
(select t1.code, min(id) as minid
from t1
group by t1.code
) t1min
on t1.id = t1min.minid left outer join
t2
on t2.t1_code = t1min.code;
这样做是将原始表连接到另一个表以查找每个代码的最小id
。通过加入id
,t1min.code
只会在最小值上显示值。最后的连接只会为这些代码带来代码。
编辑:
实际问题有点复杂。我认为最好的方法是简单地枚举每个表中的值,并使用两个键进行连接:
select t1.code, t1.field1, t1.field2, t2.t1_code, t2.var1
from (select t1.*,
@rn1 := if(@code = code, @rn1 + 1, 1) as rn, @code := code
from t1 cross join
(select @rn1 := 0, @code := '') const
order by code, id
) t1 left outer join
(select t2.*,
@rn2 := if(@code = t1_code, @rn2 + 1, 1) as rn, @code := t1_code
from t2 cross join
(select @rn2 := 0, @code := '') const
order by t1_code, t2id
) t2
on t1.code = t2.t1_code and t1.rn = t2.rn
order by t1.id;