我将一些数据导入mysql数据库并尝试清理它。
| ID |类别名称|父母姓名| PARENT_ID
1 Baseball (this is a parent)
2 Ball | Baseball | null
3 Bat | Baseball | null
4 Glove | Baseball | null
5 Basketball (this is a parent)
6 Basket | Basketball | null
7 Net | Basketball | null
如何执行UPDATE语句,以便更新每个子类别的parent_id以获得父ID?而不是
2球|棒球|空
我喜欢
2球|棒球| 1
答案 0 :(得分:4)
MySQL通常不允许您在同一个表上运行select和update,但您可以使用“派生表”来欺骗它:
UPDATE categories
SET parent_id = (
SELECT id FROM (SELECT id, name FROM categories) c
WHERE c.name=categories.parent_name
)
WHERE parent_name IS NOT NULL