从PostgreSQL中的数组转换值

时间:2018-04-18 11:41:05

标签: sql postgresql

在我的PostgreSQL数据库中,我有以下架构:

CREATE TABLE slide_results (
    id integer NOT NULL,
    tags character varying[] DEFAULT '{}'::character varying[]
);

INSERT INTO slide_results (id, tags)
    VALUES (1, '{Food, Housing}');

INSERT INTO slide_results (id, tags)
    VALUES (2, '{Security, Transport}');

现在我想让sql查询返回一个额外的列,这个列名是domain_name。此列的值取决于tags列的内容。如果tags列的值为Food,则domain_name应为I need food help,如果代码包含Transport,则domain_nameTransport help neededid | domain_name 1 | I need food help 2 | Transport help needed 所以查询的结果应该是

public function show(symptoms $symptom)
{
    return view('front.second', compact('symptom'));
}

如何在PostgreSQL中做这样的事情?

这是sql fiddle with db schema:

https://www.db-fiddle.com/f/pP7ZfNzVnisSG6xCjejqkY/0

2 个答案:

答案 0 :(得分:1)

SELECT id,CASE WHEN 'Food' = ANY(tags) THEN 'I need food help'
               WHEN 'Transport' = ANY(tags) THEN 'Transport help needed' 
          END AS domain_name 
FROM slide_results;

答案 1 :(得分:1)

您似乎需要一个表格才能将tag转换为domain_name,例如

create table tag_domain(tag text, domain_name text);
insert into tag_domain values
('Food', 'I need food help'),
('Transport', 'Transport help needed');

并以这种方式使用它:

select * 
from slide_results s
join tag_domain t on t.tag = any(s.tags)    

Db-Fiddle.