[英]Postgresql: add two values to a column separated by a comma?
我正在尝试创建一个名为 geo 的列,其中有一列组合了两个随机生成的点。 我的桌子看起来像这样。
create table data (
id SERIAL primary key,
first VARCHAR(50),
last VARCHAR(50),
g VARCHAR(50),
geo VARCHAR(100)
);
这是我尝试生成这些随机值但出现错误,因为INSERT has more expression than target columns
INSERT INTO data (first,last,g,geo)
SELECT substr(md5(random()::text), 1, 7),
substr(md5(random()::text), 1, 10),
substr(md5(random()::text), 1, 1),
(random() * (47.606209 - 25.427152)) + 25.427152 , (random() * (-124.389641 - -69.082237)) + -69.082237
FROM generate_series(1, 20);
有谁知道如何做到这一点? 另外,我知道地理位置不应该是字符串,但在我的例子中它工作得很好。 谢谢
值之间的逗号表示它们是两个不同的列。
INSERT INTO data (first,last,g,geo)
SELECT
-- first
substr(md5(random()::text), 1, 7),
-- last
substr(md5(random()::text), 1, 10),
-- g
substr(md5(random()::text), 1, 1),
-- geo
(random() * (47.606209 - 25.427152)) + 25.427152,
-- ?fifth column?
(random() * (-124.389641 - -69.082237)) + -69.082237
FROM generate_series(1, 20);
如果要连接字符串,请使用||
.
INSERT INTO data (first,last,g,geo)
SELECT
-- first
substr(md5(random()::text), 1, 7),
-- last
substr(md5(random()::text), 1, 10),
-- g
substr(md5(random()::text), 1, 1),
-- geo
(random() * (47.606209 - 25.427152)) + 25.427152 ||
',' ||
(random() * (-124.389641 - -69.082237)) + -69.082237
FROM generate_series(1, 20);
但是,将这两个数值存储为字符串会使其变慢且难以使用。 相反,使用两个numeric
列来存储这两个数字。
create table data (
id bigserial primary key,
-- Don't put artificial limits on columns, it doesn't save space.
-- They'll only use as much space as necessary.
-- Use `text` unless there's a good reason for a limit.
-- In Postgres, `text` is just an unlimited `varchar`.
first text,
last text,
g text,
geox numeric,
geoy numeric
);
INSERT INTO data (first,last,g,geox,geoy)
SELECT
-- first
substr(md5(random()::text), 1, 7),
-- last
substr(md5(random()::text), 1, 10),
-- g
substr(md5(random()::text), 1, 1),
-- geox
(random() * (47.606209 - 25.427152)) + 25.427152,
-- geoy
(random() * (-124.389641 - -69.082237)) + -69.082237
FROM generate_series(1, 20);
现在它们可以作为数字进行比较,并且可以根据需要进行格式化。
select geox || ',' || geoy from data;
更好的是,使用内置的point
类型。
create table data (
id bigserial primary key,
first text,
last text,
g text,
geo point
);
这些也可以生成为x,y
字符串并转换为一个point
。
select (random() || ',' || random())::point;
Postgres 有大量内置的二维几何函数。
如果您想做真正的 GIS,请使用PostGIS 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.