1

假设我有下表:

|   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=2 的 col1_fix 值,所以该行最终只会从行 id = 1 中获取 col2 和 col3 值)

|   ID   |   col1_fix   |   col2   |  col3   |     
    1        val1       val12     val13  
    2        val2       val12     val13        
    3        val3       val32     val33      

我正在考虑创建一个视图,以便它加入自己的表,不确定方向是否正确)。

4

2 回答 2

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
于 2015-06-14T04:43:37.473 回答
0
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;

但是,我同意 Jim Garrison 的评论,即您没有指定如果ref_id值指向的行本身具有ref_id指向另一行的值,等等,等等......

上述查询并未尝试处理这种情况。如果您需要处理这种递归要求,那么,我的理解是,您将很难使用 MySql,因为它缺少一些基本的递归功能。虽然我确信,如果需要,比我更聪明的人可以向我们展示这仍然是可行的。

于 2015-06-14T05:46:47.773 回答