我有 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/