如何在特定条件下使用MySQL或Go更新结果?

huangapple go评论77阅读模式
英文:

How to update the result with MySQL or Go in special conditions?

问题

我想在特定条件下使用MySQL或Go更新结果:

原始数据:

id    parent_id  grade_id 
test 	admin	
test1 	test 	
test2	test	
test3	test1	
test4	test	

需要更新grade_id列:

id    parent_id    grade_id 
test 	admin	
test1 	test 	admin
test2	test	admin
test3	test1	test
test4	test	admin

根据数据,如果test的父级id不为空(父级id为admin),那么下一个test1的grade id就是admin,其余的可以按照相同的方式进行处理。

英文:

I would like to update the result with MySQL or Go in special conditions:

Original data:

id    parent_id  grade_id 
test 	admin	
test1 	test 	
test2	test	
test3	test1	
test4	test	

need to update a column of grade_id:

id    parent_id    grade_id 
test 	admin	
test1 	test 	admin
test2	test	admin
test3	test1	test
test4	test	admin

According to the data, if test's parent id is not null (parent id is admin), then the next test1's grade id is admin, the rest can be done in the same manner.

答案1

得分: 1

如果我正确理解了问题,你正在寻找一种更新给定表的方法,将grade_id字段设置为使用其parent_id引用的记录的parent_id(即test1parent_idtest,而testparent_idadmin,因此grade_id应该是admin)。

可以使用以下简单的查询来完成此操作:

UPDATE foo AS f LEFT JOIN (
  SELECT ID, parent_id FROM foo
) AS j ON f.parent_id = j.ID
SET f.grade_id = j.parent_id;

可以在这里找到一个简单的示例查询进行测试。

英文:

If I understand the question correctly, you're looking for a way to update a given table, setting the grade_id field to be the parent_id of whatever record is referenced using its parent_id (ie test1 has test as parent_id, which in turn has admin as parent_id, hence the grade_id should be admin).

This can be done using a pretty simple query like this:

UPDATE foo AS f LEFT JOIN (
  SELECT ID, parent_id FROM foo
) AS j ON f.parent_id = j.ID
SET f.grade_id = j.parent_id;

A simple example of this query to play around with can be found here

huangapple
  • 本文由 发表于 2023年2月6日 16:22:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75358860.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定