gpt4 book ai didi

mySQL从同一个表的不同行中选择

转载 作者:行者123 更新时间:2023-11-30 22:42:10 25 4
gpt4 key购买 nike

假设我有下表:

|   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

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

最佳答案

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

关于mySQL从同一个表的不同行中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30825795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com