Insert.. select.. case - 有没有办法得到2列?
Insert.. select.. case - is there any way to get 2 columns?
a 有一个 table,我想在此 table 中插入一些内容(我的原创 ;P)。
所以我有:
INSERT into TARGET_TABLE ([...], tcol1, tcol2)
SELECT [...],
(SELECT
CASE
WHEN smth IS NOT NULL THEN SELECT Q_COL1 [...]
WHEN smthelse IS NOT NULL THEN SELECT Q_COL1 [from the same table but via different fk and through another tables]
END)
FROM another_table
而且效果很好。
但是
我需要另一个 table 的另一个值,它严格连接到 Q_COL1 并且可以使用 SELECT Q_COL1 部分中的一个简单 JOIN 轻松获得.
但是 (SELECT CASE ...) 应该 return 只有一个值。
Ofc 我可以再做一轮并添加另一个插入物,但我不喜欢它 - 我宁愿这样做一次,使用一个插入物。
有什么线索吗? :)
编辑:
我想通了!
INSERT INTO TARGET_TABLE([...], tcol1, tcol2)
SELECT .... COALESCE(t1c1.val1, t2c1.val1), COALESCE(t1c2.val2, t2c2.val2)
FROM another_table
JOIN table_in_between1..
JOIN table_in_between2..
JOIN table_for_col1 t1c1 ON t1c1.Id=table_in_between1.idt1c1
JOIN table_for_col1 t2c1 ON t2c1.Id=table_in_between2.idt2c1
JOIN table_for_col2 t1c2 ON t1c2.Id = t1c1.id..
JOIN table_for_col2 t2c2 ON t2c2.Id = t2c1.Id...
此外,执行计划现在好多了(没有流聚合和急切的假脱机)。
INSERT INTO TARGET_TABLE([...], tcol1, tcol2)
SELECT .... COALESCE(t1c1.val1, t2c1.val1), COALESCE(t1c2.val2, t2c2.val2)
FROM another_table
JOIN table_in_between1..
JOIN table_in_between2..
JOIN table_for_col1 t1c1 ON t1c1.Id=table_in_between1.idt1c1
JOIN table_for_col1 t2c1 ON t2c1.Id=table_in_between2.idt2c1
JOIN table_for_col2 t1c2 ON t1c2.Id = t1c1.id..
JOIN table_for_col2 t2c2 ON t2c2.Id = t2c1.Id...
此外,执行计划现在好多了(没有流聚合和急切的假脱机)。
a 有一个 table,我想在此 table 中插入一些内容(我的原创 ;P)。
所以我有:
INSERT into TARGET_TABLE ([...], tcol1, tcol2)
SELECT [...],
(SELECT
CASE
WHEN smth IS NOT NULL THEN SELECT Q_COL1 [...]
WHEN smthelse IS NOT NULL THEN SELECT Q_COL1 [from the same table but via different fk and through another tables]
END)
FROM another_table
而且效果很好。
但是
我需要另一个 table 的另一个值,它严格连接到 Q_COL1 并且可以使用 SELECT Q_COL1 部分中的一个简单 JOIN 轻松获得.
但是 (SELECT CASE ...) 应该 return 只有一个值。
Ofc 我可以再做一轮并添加另一个插入物,但我不喜欢它 - 我宁愿这样做一次,使用一个插入物。
有什么线索吗? :)
编辑: 我想通了!
INSERT INTO TARGET_TABLE([...], tcol1, tcol2)
SELECT .... COALESCE(t1c1.val1, t2c1.val1), COALESCE(t1c2.val2, t2c2.val2)
FROM another_table
JOIN table_in_between1..
JOIN table_in_between2..
JOIN table_for_col1 t1c1 ON t1c1.Id=table_in_between1.idt1c1
JOIN table_for_col1 t2c1 ON t2c1.Id=table_in_between2.idt2c1
JOIN table_for_col2 t1c2 ON t1c2.Id = t1c1.id..
JOIN table_for_col2 t2c2 ON t2c2.Id = t2c1.Id...
此外,执行计划现在好多了(没有流聚合和急切的假脱机)。
INSERT INTO TARGET_TABLE([...], tcol1, tcol2)
SELECT .... COALESCE(t1c1.val1, t2c1.val1), COALESCE(t1c2.val2, t2c2.val2)
FROM another_table
JOIN table_in_between1..
JOIN table_in_between2..
JOIN table_for_col1 t1c1 ON t1c1.Id=table_in_between1.idt1c1
JOIN table_for_col1 t2c1 ON t2c1.Id=table_in_between2.idt2c1
JOIN table_for_col2 t1c2 ON t1c2.Id = t1c1.id..
JOIN table_for_col2 t2c2 ON t2c2.Id = t2c1.Id...
此外,执行计划现在好多了(没有流聚合和急切的假脱机)。