簡體   English   中英

Postgresql:將兩個值添加到以逗號分隔的列?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM