MySQL 根据 col1 的值是否存在于 col2 和 col3 = 值来更新 col4

MySQL update col4 based on whether value from col1 exists in col2 and col3 = value

我有一个具有以下结构的 table(命名单元):

id     type     type_id     name     parent     hide
====================================================
12     child       2         no1-r     36        0
32     child       2         no2-l     0         0
36     parent      1         no1       0         0
42     parent      1         no4       0         0
59     child       2         no5-t     0         0
60     child       2         no6-r     72        0
63     child       2         no6-l     72        0
72     parent      1         no6       0         0
81     parent      1         no7       0         0
94     parent      1         no8       0         0
95     parent      1         no9       0         0
97     child       2         no9-r     95        0
99     child       2         no9-t     95        0

我想做的是遍历所有 id,如果 id 在父级中不存在并且 type_id = 1,则将 hide 设置为 1。所以我的输出 table 将导致:

id     type     type_id     name     parent     hide
====================================================
12     child       2         no1-r     36        0
32     child       2         no2-l     0         0
36     parent      1         no1       0         0
42     parent      1         no4       0         1
59     child       2         no5-t     0         0
60     child       2         no6-r     72        0
63     child       2         no6-l     72        0
72     parent      1         no6       0         0
81     parent      1         no7       0         1
94     parent      1         no8       0         1
95     parent      1         no9       0         0
97     child       2         no9-r     95        0
99     child       2         no9-t     95        0

所以基本上是因为 id 的 42、81 和 94 在父级中不存在,所以它们的隐藏值设置为 1。而 id 36 确实存在于父级中,因此不受影响,而且 id 32 也不受影响,即使它在父级中不存在,因为它的 type_id 是 2.

我这辈子都想不通 MySQL(运行ning ver 5.6.44)更新到 运行 这个 table 的目的这个输出,所以任何帮助将不胜感激!

您可以在 UPDATE 语句中使用 self LEFT 加入:

UPDATE units u1
LEFT JOIN units u2 ON u2.parent = u1.id
SET u1.hide = 1
WHERE u1.type_id = 1 AND u2.id IS NULL

参见demo
结果:

> id | type   | type_id | name  | parent | hide
> -: | :----- | ------: | :---- | -----: | ---:
> 12 | child  |       2 | no1-r |     36 |    0
> 32 | child  |       2 | no2-l |      0 |    0
> 36 | parent |       1 | no1   |      0 |    0
> 42 | parent |       1 | no4   |      0 |    1
> 59 | child  |       2 | no5-t |      0 |    0
> 60 | child  |       2 | no6-r |     72 |    0
> 63 | child  |       2 | no6-l |     72 |    0
> 72 | parent |       1 | no6   |      0 |    0
> 81 | parent |       1 | no7   |      0 |    1
> 94 | parent |       1 | no8   |      0 |    1
> 95 | parent |       1 | no9   |      0 |    0
> 97 | child  |       2 | no9-r |     95 |    0
> 99 | child  |       2 | no9-t |     95 |    0