如何存储在一行数组中的所有值在postgresql?



我有以下表格

tbody> <<tr>2
学生Id 科目A 科目B 科目C 科目D
1988776100
901006471

Postgres有一个数组数据类型。您可以添加这种数据类型的新列,并将数据复制到该格式。

如果原始表是这样定义的:

create table scores (
studentid int, 
subjectA int, 
subjectB int, 
subjectC int, 
subjectD int);

然后添加一个新列(这可以是一个一维或多维数组,参考https://www.postgresql.org/docs/current/arrays.html:

alter table scores add column subjectArray int[4];

并将数据保存到该列:

update scores set subjectArray=ARRAY[subjectA,subjectB,subjectC,subjectD];

然后你可以选择单独的值,像这样:

select subjectArray[2] from scores where studentid=1;

或者像这样选择整个数组:

select studentid, subjectArray from scores where studentid=1;

这个主题可能已经在这里回答了,但是你也可以添加json类型的列来更容易地保存数据。在您的情况下,您将数据保存为字符串(作为有效的json),并且通过检索它,您将再次将其格式化为数组。

关于json列的文档。

最新更新