Mysql 获取父id为null的记录,并用“父id”=id的记录替换数据
我有一张桌子:Mysql 获取父id为null的记录,并用“父id”=id的记录替换数据,mysql,database,Mysql,Database,我有一张桌子: +-------+-------------+-----------+-------------+ | ID | parent_id | name | other_data | +-------+-------------+-----------+-------------+ | 1 | null | name | ... | | 2 | null | name1 | ...
+-------+-------------+-----------+-------------+
| ID | parent_id | name | other_data |
+-------+-------------+-----------+-------------+
| 1 | null | name | ... |
| 2 | null | name1 | ... |
| 3 | null | name2 | ... |
| 4 | 2 | name1new | ... |
| 5 | 3 | name2new | ... |
| 6 | 3 | name2new2 | ... |
+-------+-------------+-----------+-------------+
我需要所有父项id为空的记录。简单查询可以如下所示:
SELECT id, name
FROM `table`
WHERE `parent_id` IS NULL
LIMIT 0 , 30
它将返回3条记录:
1 name;
2 name1;
3 name2
我想要的是获得这3条记录,但用来自元素的新值替换第二条记录,这些元素的父id为当前id,例如,第4行具有父id 2,因此第二行中的新数据必须来自第4行。但两者都有:第5行和第6行都有父_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试试这个:
我得到了一个错误:MySQL服务器版本的正确语法使用了near'case when t2.parent_id不为null,然后t2.name else t1.name end as new_name fr'在第3行,对此表示担忧。立即尝试:获得相同的错误。但是如果我在新的id后面用逗号就可以了。但是要找到mutch记录:1个名字;4.名称1新;5名2名新成员;6.2新名称;1248-每个派生表都必须有自己的别名-erroroh再次为语法错误感到抱歉:检查更新的ans:如果有帮助,您应该接受答案:I will。但是您应该删除错误:P
$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);
}
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
;