[英]Update record in DB based on parentId and min value
I have a table like this.我有一张这样的桌子。
ID | ParentId | Level | LevelStatus
1 1 5 NULL
2 1 6 NULL
3 2 4 NULL
4 2 2 NULL
5 3 2 NULL
I need to update the column LevelStatus with value 1 for each minimum level of the parentId.对于 parentId 的每个最低级别,我需要使用值 1 更新列 LevelStatus。 For example the lowest level for parentId 1 is Level 5 so it should only update that record, for parentId 2 it should update the record where level is 2.例如,parentId 1 的最低级别是级别 5,因此它应该只更新该记录,对于 parentId 2,它应该更新级别为 2 的记录。
I know how to select the right records.我知道如何选择正确的记录。 Something like this:像这样的东西:
SELECT DISTINCT ParentId, MIN(Level) AS MinLevel
FROM TableA
GROUP BY ParentId
But don't know how to use it to write the update statement.但是不知道怎么用它来写更新语句。
You can use a correlated subquery:您可以使用相关子查询:
update tablea
set levelstatus = 1
where level = (select min(a2.level)
from tablea a2
where a2.parentid = a.parentid
);
This is standard SQL syntax and should work in every database .这是标准的 SQL 语法,应该适用于每个数据库。 . . . . other than MySQL and MariaDB.除了 MySQL 和 MariaDB。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.