MYSQL 更新嵌套子查询

标签 mysql sql subquery

我有 3 个这种格式的表:

表 child :

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

表父级:

id|grandparent_id
1          1
2          1
3          2

表祖 parent :

id
1          
2          

我需要运行一个查询,根据父表中的 grandparent_id 更新子表中的 grandparent_id 列。所以 Child 表的正确最终形式是: 表 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

最佳答案

您可以使用以下查询获取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;

Demo: http://sqlfiddle.com/#!9/894e97/1/0 (modified table content to show the UPDATE is working).

Hint: Your "correct" example is wrong: GrandParent of Parent with id = 2 is 1!

关于MYSQL 更新嵌套子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43663979/

相关文章:

mysql - sql查询计数连接中的记录数

Javascript 将表单发送到 PHP

MySQL - 1075 表定义不正确,只能有一个自动列,并且必须将其定义为键

MYSQL使用join查询多表

php - 如何加速Mysql和PHP?

mysql - 如何在 SQL 中转置表

c# - 使用手动事务和分层事务进行单元测试

MySQL - 有可能加快 MySQL 的计数吗?

mysql - subselect 使复杂的查询真的很慢

php - Laravel 5.2 中 Select 语句中的子查询