MySQL在update中使用select语句设置为null

时间:2018-01-09 09:03:06

标签: mysql select nested sql-update

我试图以我描述的方式更新树。我有一个深度为5的树,叶节点的值大于0.现在,对于每个父节点,我想计算子节点中访问量最大的值并为其自身设置该值。到现在为止,我试图这样做:

update itmanagement.PRC_processes parent
set MainStructID = (case when (select MainStructID
from (select * from itmanagement.PRC_processes) child
where parent.ProcessID = child.ParentID
group by MainStructID
order by count(*)
limit 1) is null then 0 else (select MainStructID
from (select * from itmanagement.PRC_processes) child
where parent.ProcessID = child.ParentID
group by MainStructID
order by count(*)
limit 1) end),
SubStructID = (case when (select SubStructID
from (select * from itmanagement.PRC_processes) child
where parent.ProcessID = child.ParentID
group by SubStructID
order by count(*)
limit 1) is null then 0 else (select SubStructID
from (select * from itmanagement.PRC_processes) child
where parent.ProcessID = child.ParentID
group by SubStructID
order by count(*)
limit 1) end)
where ProcessID > 0 and MainStructID = 0 and SubStructID = 0;

但在运行上述查询后,没有任何变化。例如,id为ProcessID = 24的行保留以前的值0.但是下面的查询返回值:

select SubStructID
from (select * from itmanagement.PRC_processes) child
where child.ParentID = 24
group by SubStructID
order by count(*)
limit 1;

我自己的猜测是select语句返回一个表(也只有一行),并且它在赋值时不起作用。

那么问题是什么以及如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我终于改变了查询以其他方式工作。 而且我也利用了@ Solarflare的答案来提高效率。

现在查询如下所示。我希望它能帮助别人:

update itmanagement.PRC_processes parent
join (select child.ParentID ParentID
, (select MainStructID from itmanagement.PRC_processes childer where childer.ParentID = child.ParentID group by MainStructID order by count(*) desc LIMIT 1) maxSeenMainStructID
, (select SubStructID from itmanagement.PRC_processes childer where childer.ParentID = child.ParentID group by SubStructID order by count(*) desc LIMIT 1) maxSeenSubStructID
from itmanagement.PRC_processes child
where child.ParentID is not null
group by child.ParentID) calcProcesses on parent.ProcessID = calcProcesses.ParentID
set parent.MainStructID = coalesce(calcProcesses.maxSeenMainStructID, 0)
,parent.SubStructID = coalesce(calcProcesses.maxSeenSubStructID, 0)
where parent.ProcessID > 0 and parent.MainStructID = 0 and parent.SubStructID = 0;

现在一切都很顺利。