【问题标题】:How to update the result with MySQL or Go in special conditions?如何在特殊情况下使用 MySQL 或 Go 更新结果?
【发布时间】:2023-02-06 18:40:30
【问题描述】:

我想在特殊情况下用 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的parent id不为null(parent id为admin),则下一个test1的年级id为admin,其余同理。

【问题讨论】:

  • 我没有看到一个实际的问题。你能用你正在尝试的代码更新你的问题,并准确解释它是如何不按预期工作的吗?

标签: mysql go


【解决方案1】:

如果我正确理解了这个问题,您正在寻找更新给定表的方法,将 grade_id 字段设置为使用其 parent_id 引用的任何记录的 parent_id(即 test1 具有 @987654326 @作为parent_id,而admin作为parent_id,因此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;

can be found here 一起使用的此查询的一个简单示例

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-12
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多