我需要有关如何将列组合到同一个表中的一个新列的基本帮助。我已经完成了以下作为SELECT命令,它工作正常。我只是不知道如何永久地将它添加到表中,以便它成为表的一部分。
SELECT *, concat(z41, z42, z43, z44) AS option_3,
concat(z411, z412, z413, z421, z422, z423, z431, z432, z433, z434, z444,z443, z442, z441) AS option_4,
concat(z4211, z4212, z4213, z4214, z4215, z4311, z4312, z4313, z4314, z4431, z4432, z4433, z4434, z4421, z4422, z4423, z4424, z4425, z4426) AS option_5
FROM combined_full
答案 0 :(得分:0)
“以便它成为表格的一部分” - 你不能。不幸的是Postgres(截至9.6)没有(持久的)计算列。
如果表达式的计算成本不是很高,而且你不需要索引,我建议创建一个包含表达式的视图。
鉴于您的问题中的示例,在您的情况下这应该足够好,因为连接值并不是那么昂贵。
如果您确实认为需要持续计算表达式,例如如果要在其上创建索引,或者在where
子句中不断使用该表达式,则需要向表中添加常规列以及在插入或更新行时更新表达式的触发器。
答案 1 :(得分:0)
Like others have mentioned, you are probably better off using a view. But if you really need this computed data in column then you can do this:
ALTER TABLE combined_full ADD COLUMN option_3 varchar,
ADD COLUMN option_4 varchar,
ADD COLUMN option_5 varchar;
UPDATE combined_full
SET option_3 = concat(z41, z42, z43, z44),
option_4 = concat(z411, z412, z413, z421, z422, z423, z431, z432, z433, z434, z444,z443, z442, z441),
option_5 = concat(z4211, z4212, z4213, z4214, z4215, z4311, z4312, z4313, z4314, z4431, z4432, z4433, z4434, z4421, z4422, z4423, z4424, z4425, z4426);
When adding new rows to the table, you should either also enter values for these three new columns, or create an insert trigger so that the values are automatically calculated as you do above.