mysql - 获取父 ID 为空的记录,并用具有 'parent id' =id 的记录替换数据

标签 mysql database

我有 table :

+-------+-------------+-----------+-------------+
| 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 为空的记录。简单的查询可以是这样的:

    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;

感谢@Vishal Zanzrukia 的帮助

最佳答案

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
;

关于mysql - 获取父 ID 为空的记录,并用具有 'parent id' =id 的记录替换数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28339355/

相关文章:

c# - 如何通过c#访问localhost连接MySQL数据库?

php - 我可以使用什么机制来订购阵列?

PHP 用 mysqli 变慢

mysql - 正向工程一些新关系在填充数据库中失败(errno 150)

php - 如何使用一个查询更新多行

mysql - 使用 phpmyadmin Cpanel 为 mysql 设置复制服务器

php - 简单的照片分享网站 : How to structure the MySQL database for multiple users and their photos

php - MYSQL PHP通过html形式更新db表信息

mysql - 在 Kohana 查询中使用表别名?

数据库部署 - 生成部署计划期间发生错误。部署无法继续