一个专栏

时间:2017-06-16 14:24:41

标签: postgresql

我有一些sql,它有一些硬编码值,我试图用数据库列中的值替换

with pre as (
with a(k, v) as (select id, my_column from mytable), 
col(s, n) as (select * from unnest(array['Title', 'First', 'Middle', 'Last']) with ordinality c (s, n))

我试图用这样的东西替换不需要的sql:

select unnest(string_to_array(my_column, ':')) as elements from mytable

mycolumn内容的长度各不相同,但是一个例子可能是title = aaa:first = bbb:middle = ccc:last = ddd

由于

1 个答案:

答案 0 :(得分:0)

我的答案基于on your previous post。以下是如何将unnest(string_to_array(my_column, ':'))与命名列连接在一起的示例:

t=# with a as (select id,k,v from my_table, unnest(string_to_array(my_column, ':')) with ordinality as t(k,v))
, col(s, n) as (select * from unnest(array['Title', 'First', 'Middle', 'Last']) with ordinality c (s, n))
select * from a join col on n=v;
 id |     k      | v |   s    | n
----+------------+---+--------+---
  1 | title=aaa  | 1 | Title  | 1
  1 | first=bbb  | 2 | First  | 2
  1 | middle=ccc | 3 | Middle | 3
  1 | last=ddd   | 4 | Last   | 4
(4 rows)

当然,您必须以不同方式加入(根据您之前的帖子)。但如果不清楚的部分是你如何从表中选择而不是从值中选择,那么上面的例子应该会有所帮助。

<强>更新

将值放到表格中:

t=# create table keys(t text);
CREATE TABLE
Time: 91.908 ms
t=# insert into keys select unnest(array['Title', 'First', 'Middle', 'Last']);
INSERT 0 4
Time: 11.552 ms
t=# select * from keys ;
   t
--------
 Title
 First
 Middle
 Last
(4 rows)

现在加入密钥表:

t=# with a as (select id,k,v from my_table, unnest(string_to_array(my_column, ':')) with ordinality as t(k,v))
select * from a join keys on split_part(k,'=',1) = lower(t);
 id |     k      | v |   t
----+------------+---+--------
  1 | first=bbb  | 2 | First
  1 | last=ddd   | 4 | Last
  1 | middle=ccc | 3 | Middle
  1 | title=aaa  | 1 | Title
(4 rows)