
[英]SQLite: How to retrieve data from column in one table using SELECT to insert retrieved data in another table
[英]Update or insert data from a table to another while the column name retrieved from other table
我要实现的内容如下:具有 my_index(主键)、updated_time、my_col_1、my_col_2 列的表目标,数据应如下所示,每当一个值进入表源时,表目标中的相应行应更新,和 updated_time 也是如此。 这些列将只是表 def 的子集。 所以我认为一旦从调用者那里收到列,就需要创建表目标。
表target
:
my_index | updated_time | ABC | DEF | GHI
---------+-------------------------+-----+-----+------
12 | 2021-05-11 01:01:01.000 | 1.0 | 2.0 | 3.0
具有列 id(自动增量主键)、my_index、my_id、my_value 的表source
,数据应如下所示:
id | my_index | my_id | my_value
---+----------+-------+---------
1 | 12 | 3 | 1.0
2 | 12 | 4 | 2.0
3 | 12 | 5 | 3.0
4 | 11 | 6 | 4.0
虽然 table target 中的列来自另一个 table def
列my_id
(主键), my_col
,但数据应如下所示:
my_id | my_col
------+--------
3 | ABC
4 | DEF
5 | GHI
6 | JKL
我不确定如何实现 SQL 命令从表源获取数据,然后更新或插入表目标。
有人可以帮忙吗? 欣赏它。
这实际上不是一个很好的数据 model - 将列的名称存储在一个表中以便在另一个表中进行更新是很棘手的。 SQL 不能很好地处理变量列名。
你可以做你想做的事,但你必须明确列出列。 这个想法是汇总源表以获取每个潜在列的值。 然后,当源列中有值时,设置目标列中的值:
update t
set abc = (case when s.abc is not null then s.abc else t.abc end),
def = (case when s.def is not null then s.def else t.def end),
ghi = (case when s.ghi is not null then s.ghi else t.ghi end)
from target t join
(select s.my_index,
max(case when d.my_col = 'ABC' then s.my_value end) as abc,
max(case when d.my_col = 'DEF' then s.my_value end) as def,
max(case when d.my_col = 'GHI' then s.my_value end) as ghi
from source s join
def d
on s.my_id = d.my_id
group by s.my_index
) s
on s.my_index = t.my_index
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.