获取父id为null的记录,并将数据替换为具有'parent id'= id的记录

时间:2015-02-05 08:30:17

标签: mysql database

我有桌子:

+-------+-------------+-----------+-------------+
| ID    | parent_id   | name      | other_data  | 
+-------+-------------+-----------+-------------+
| 1     |  null       | name      | ...         |
| 2     |  null       | name1     | ...         |
| 3     |  null       | name2     | ...         |
| 4     |  2          | name1new  | ...         |
| 5     |  3          | name2new  | ...         |
| 6     |  3          | name2new2 | ...         |
+-------+-------------+-----------+-------------+  

我需要parent_id为null的所有记录。简单查询可以是:

    SELECT id, name
        FROM  `table` 
        WHERE  `parent_id` IS NULL 
        LIMIT 0 , 30

它将返回3条记录:

 1 name;
 2 name1;
 3 name2

我想要的是获取这3条记录,但用来自具有parent_id作为当前ID的元素的新值替换第二条(例如,4行具有parent_id 2,因此在第二行中,新数据必须来自第4行。但是两者:第5行并且第6行具有parent_id 3,因此3行必须具有来自第6行的数据 - 较新的一行。 我需要结果如:

1 name; 
4 name1new;
6 name2new2;

解决:

SELECT
(CASE WHEN  `t2`.`parent_id` is NOT NULL THEN `t2`.`id` ELSE `t1`.`id` END) as `new_id`,
(CASE WHEN  `t2`.`parent_id` is NOT NULL THEN `t2`.`name` else `t1`.`name` END) as `new_name`
FROM `table` as `t1` LEFT JOIN `table` as `t2` on (`t1`.`id` = `t2`.`parent_id` AND `t2`.`some_id` = '6') WHERE `t1`.`parent_id` IS NULL;

THX寻求帮助@Vishal Zanzrukia

2 个答案:

答案 0 :(得分:0)

试试这个:

$sql="select parent_id,name from table where parent_id  IS NOT NULL  group by parent_id";
while($r= mysql_fetch_array(mysql_query($sql))){
    $sql2="update table set name='$r[name]' where ID=$r[parent_id]  and parent_id  IS NULL ";
    mysql_query($sql2);

}

答案 1 :(得分:0)

select 
tmp1.new_id,
tmp1.new_name
from
(select
    (case when  t2.parent_id is not null then t2.ID else t1.ID end) as new_id,
    (case when  t2.parent_id is not null then t2.name else t1.name end) as new_name,
    (case when  t2.parent_id is not null then t2.parent_id else concat(t1.id,t1.name) end) as parent_id
    from table t1 left join table t2 on t1.ID = t2.parent_id group by new_id) tmp1
left join
(select
    (case when  t2.parent_id is not null then t2.ID else t1.ID end) as new_id,
    (case when  t2.parent_id is not null then t2.name else t1.name end) as new_name,
    (case when  t2.parent_id is not null then t2.parent_id else concat(t1.id,t1.name) end) as parent_id
    from table t1 left join table t2 on t1.ID = t2.parent_id group by new_id) tmp2
on (tmp1.parent_id = tmp2.parent_id and tmp1.new_id < tmp2.new_id)
where tmp2.new_id is null
;