Mysql使用父名更新父类别ID

时间:2015-04-16 11:31:29

标签: php mysql

我有像这样的MYSQL表

id     category_name                parent_name            parent_id
1      Animals & Pet Supplies       NULL                       0
2      Live Animals                 Animals & Pet Supplies     0
3      Pet Supplies                 Animals & Pet Supplies     0
4      Bird Supplies                Pet Supplies               0
5      Bird Cage Accessories        Bird Supplies              0

现在我想更新class_name中id为parent_name的parent_id 如下所示

id     category_name                parent_name            parent_id
1      Animals & Pet Supplies       NULL                       0
2      Live Animals                 Animals & Pet Supplies     1
3      Pet Supplies                 Animals & Pet Supplies     1
4      Bird Supplies                Pet Supplies               3
5      Bird Cage Accessories        Bird Supplies              4

默认情况下,父id的值为0,如果parent_name = NULL则应为0,否则应使用category_name的相应id更新。

2 个答案:

答案 0 :(得分:1)

我想它应该是这样的:

UPDATE my_table SET parent_id=
   (SELECT id FROM my_table t1 WHERE t1.name=my_table.parent_name)
   WHERE parent_name IS NOT NULL;

虽然mysql可能会拒绝同一个表的嵌套SELECT查询,但在这种情况下,您可能需要创建一个新的临时表,如下所示:

CREATE TEMPORARY TABLE my_table_temp AS SELECT * FROM my_table;
UPDATE my_table SET parent_id=
   (SELECT id FROM my_table t1 WHERE t1.name=my_table.parent_name)
   WHERE parent_name IS NOT NULL;
DROP TEMPORARY TABLE my_table_temp;

答案 1 :(得分:1)

您可以使用update with left join

轻松完成
update 
table_name t1 
left join table_name t2 on t1.parent_name = t2.category_name
set t1.parent_id = coalesce(t2.id,0) ;