简体   繁体   English

如何将数组与 PostgreSQL 中的表连接起来

[英]How can I join an array with a table in PostgreSQL

I created the following array and I want to join this with CTE of a totally different table我创建了以下数组,我想将它与一个完全不同的表的 CTE 连接起来

   CREATE TABLE places (
    name            text,
    labels         text[]
);

INSERT INTO places
    VALUES ('Places',
    ARRAY['store', 'hospital', 'home']);

I want to pass these constant values into my select statement.我想将这些常量值传递到我的 select 语句中。

    SELECT 
        e.address

    FROM env e

so It can be like所以它可以像

SELECT 
'Cashier.' ||places[1] ||'.'|| e.address,
'Doctor.' ||places[2] || '.'||e.address,
'Wife.' ||places[3] ||'.'||e.address

FROM env e

and it will be shown as它将显示为

Cashier.store.NY
Doctor.hospital.DC
Wife.house.CA

in the resulting table在结果表中

I couldn't find anything in the documentation.我在文档中找不到任何东西。 There are no mutual ids I can join this array on the table with.没有我可以在桌子上加入这个数组的相互 id。

I was wondering how this can be done/ or is it even possible or do I have to alter the table and add a column instead of using an array?我想知道如何做到这一点/甚至有可能,还是我必须更改表并添加一列而不是使用数组?

You can use CROSS JOIN , try something like:您可以使用CROSS JOIN ,尝试类似:

SELECT 
'Cashier.' || p.labels[1] ||'.'|| e.address,
'Doctor.' || p.labels[2] || '.'|| e.address,
'Wife.' || p.labels[3] ||'.'|| e.address
FROM env e
CROSS JOIN places AS p
WHERE p.name = 'Places'

Maybe something like this?也许是这样的?

 CREATE TABLE env ( name varchar(30) primary key, label text[] ); INSERT INTO env (name, label) VALUES ('Places', ARRAY['store', 'hospital', 'home']); CREATE TABLE data ( id serial primary key, address text[] ); INSERT INTO data (address) VALUES (ARRAY['store 1', 'hospital 1', 'home 1'])
 SELECT id, CONCAT_WS('.', 'Cashier', place.label[1], e.address[1]) AS place1, CONCAT_WS('.', 'Doctor', place.label[2], e.address[2]) AS place2, CONCAT_WS('.', 'Husband', place.label[3], e.address[3]) AS place3 FROM data AS e JOIN env AS place ON place.name = 'Places'
 id |编号 | place1 |地点1 | place2 |地点2 | place3 -: |:-------------------- |:------------------------- |:------------------ 1 |地点 3 -: |:-------------------- |:------------------------ -- |:----------------- 1 | Cashier.store.store 1 |收银员.store.store 1 | Doctor.hospital.hospital 1 |医生.医院.医院 1 | Husband.home.home 1丈夫.home.home 1

db<>fiddle here db<> 在这里摆弄

But it's normally not done via arrays.但这通常不是通过 arrays 完成的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM