【问题标题】:MYSQL update with nested subquery带有嵌套子查询的 MYSQL 更新
【发布时间】:2017-04-27 17:07:00
【问题描述】:

我有 3 个这种格式的表格:

表子:

id|parent_id|grandparent_id
1  1         null
2  2         null
3  3         null

父表:

id|grandparent_id
1          1
2          1
3          2

表祖父:

id
1          
2          

我需要运行一个查询,根据 Parent 表中的 grandparent_id 更新 Child 表中的 grandparent_id 列。所以 Child 表的正确最终形式将是: 表子:

id|parent_id|grandparent_id
1  1         1
2  2         1
3  3         2

这是我目前的查询,但它返回多于 1 行,这是错误的:

update child set grandparent_id = (
  select gpd.id from GrandParent gp, Parent p 
  where p.grandparent_id = gp.id) 
where 1

【问题讨论】:

    标签: mysql sql subquery nested-queries


    【解决方案1】:

    您可以使用以下查询获取UPDATE

    UPDATE Child SET Child.grandparent_id = (
        SELECT GrandParent.id 
        FROM GrandParent INNER JOIN Parent ON GrandParent.id = Parent.grandparent_id
        WHERE Parent.id = parent_id
    ) WHERE Child.grandparent_id IS NULL;
    

    演示: http://sqlfiddle.com/#!9/894e97/1/0 (修改表格内容以显示 UPDATE 正在工作)

    提示:您的“正确”示例是错误的:Parent 中的GrandParentid = 21

    【讨论】:

    • 感谢它的工作。所以我不得不内部加入而不是正常加入?为什么我不能只说 where 1 即使它不为空,也要在所有东西上运行它?
    • 如果你想UPDATE all Childs 你不需要WHERE 部分,你可以删除它(不需要WHERE 1)。我会选择INNER JOIN 加入表格。
    【解决方案2】:

    请尝试以下查询:

    Update child c,parent p
    set c.grandparent_id = p.grandparent_id
    where c.id = parent.id 
    and c.grandparent_id = ' '
    

    【讨论】:

      猜你喜欢
      • 2012-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-13
      • 1970-01-01
      • 2012-11-21
      • 2013-01-07
      相关资源
      最近更新 更多