在我的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_name
将Transport help needed
。id | 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:
答案 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)