假设我有下表:
| ID | col1_fix | col2 | col3 | ref_ID
1 val1 val12 val13
2 val2 val22 val23 1
3 val3 val32 val33
我应该使用什么语句输出到:(行id = 2有ref_id = 1所以不是获取它的值,而是从行id = 1得到值,但我想保留行id =的col1_fix值= 2,所以这一行最终只会从行id = 1)获得col2和col3值
| ID | col1_fix | col2 | col3 |
1 val1 val12 val13
2 val2 val12 val13
3 val3 val32 val33
我正在考虑创建一个视图,因此它将加入自己的表,而不确定它是否正确的方向。)
答案 0 :(得分:0)
create table t1
(
id int not null auto_increment primary key,
col1 int not null,
col2 int not null,
col3 int not null,
ref_id int null
);
insert t1 (col1,col2,col3,ref_id) values (1,2,3,null);
insert t1 (col1,col2,col3,ref_id) values (222,223,224,null);
insert t1 (col1,col2,col3,ref_id) values (333,334,335,null);
insert t1 (col1,col2,col3,ref_id) values (444,445,446,null);
insert t1 (col1,col2,col3,ref_id) values (555,556,557,3);
insert t1 (col1,col2,col3,ref_id) values (666,667,668,2);
select one.id,
( case when one.ref_id is null then one.col1 else two.col1 end
) as col1,
( case when one.ref_id is null then one.col2 else two.col2 end
) as col2,
( case when one.ref_id is null then one.col3 else two.col3 end
) as col3
from t1 one
left join t1 two
on two.id=one.ref_id
答案 1 :(得分:0)
TreeSet
但是,我同意Jim Garrison的评论,如果select curr.id,
curr.col1_fix,
case when other.id is null then curr.col2 else other.col2 end as col2,
case when other.id is null then curr.col3 else other.col3 end as col3
from the_table as curr
left join the_table as other
on other.id = curr.ref_id;
值指向一个本身具有ref_id
值的行,那么您没有指定该怎么做到另一行,依此类推......等等。
以上查询并未尝试处理该情况。如果你需要处理那种递归需求,那么,我的理解是你很难使用MySql,因为它缺少一些基本的递归功能。虽然我确信,如果需要,比我更聪明的人可以向我们展示这仍然是可行的。