假设我有一个查找表mylookup(lkid,lkname,...)
然后我还有其他两个表:
mytab(id, parentid, name, lookname, ...)
yourtab(id, parentid, ...) --id, parentid coming from mytab
然后我有一个更新尝试获取lkid和它的父lkid,sql像:
update yourtab set columnx =
case
when (select lkid from mylookup a join mytab b on a.lkname = b.lkname where b.id = c.parentid ) > 3
and (select lkid from mylookup a join mytab b on a.lkname = b.lkname where b.id = c.parentid ) >
(select lkid from mylookup where lkname = c.lkname )
then 1
else 0
end
from yourtab c
这个sql性能不好。 (从mylookup中选择lkid,在a.lkname = b.lkname上加入mytab b,其中b.id = c.parentid)为yourtb中的每一行调用2次。
如何重写sql以提高此案例的性能?
答案 0 :(得分:0)
也许是这样的......
未经测试需要一个带有一些示例数据的SQLFiddle才能真正理解内部工作原理。
Update yourtab set columnx =
case when not null (
SELECT lkid
FROM mylookup a
INNER join mytab b
on a.lkname = b.lkname
WHERE b.id = c.parentid
and a.lkid > 3
and a.lkname > c.lkname) then 1
else 0
end
FROM yourtab c
答案 1 :(得分:0)
update yourtab
set columnx = 1
FROM yourtab c
join mylookup a
on a.lkname > c.lkname
and a.lkid > 3
join mytab b
on a.lkname = b.lkname
and b.id = c.parentid
where columnx <> 1
update yourtab
set columnx = 0
FROM yourtab c
left join mylookup a
on a.lkname > c.lkname
and a.lkid > 3
left join mytab b
on a.lkname = b.lkname
and b.id = c.parentid
where columnx <> 0
and ( a.lkname is null or b.id is null )
两个语句,但如果值已经正确,则会保存锁定