Table1 Table2
id name ! id number
1 cat ! 1 10
2 dog ! 2 null
3 bat ! 3 null
4 rat ! 4 11
5 kong ! 5 null
Select *
FROM Table1 t0 left join Table2 T1 on T1.id = T2.id
id name number
1 cat 10
2 dog null
3 bat null
4 rat 11
5 kong null
I want
id name number
1 cat 10
2 dog 10
3 bat 10
4 rat 11
5 kong 11
我需要更新sql表中的数字
我的问题:我找不到适合这里的逻辑,以至于where条件应该适用于所有这三种情况,因此它不应该破坏现有的功能。
答案 0 :(得分:1)
您可以使用COALESCE
和子查询:
Select T1.ID, T1.Name,
COALESCE(T2.Number, (SELECT Number
FROM Table2
WHERE Table2.Number IS NOT NULL
AND Table2.ID < T1.ID
ORDER BY Table2.ID DESC
LIMIT 1)) AS Number
FROM Table1 T1
left join Table2 T2
on T1.id = T2.id
答案 1 :(得分:0)
Select t1.id, name, t2.id,
if(isnull(t2.number), @n, @n:=t2.number) number
FROM Table1 t1
left join Table2 t2
on T1.id = T2.id,
(select @n:=0) n