PostgreSQL integer array value join to integer in other table with desc string

可紊 提交于 2019-12-12 10:37:03

问题


I have a table test column with int arrays and values like {1000,4000,6000} or {1000} or {1000,4000} called ekw. These values match to a description string in another table

tab: test
id | name   | ekw
-----------------
 1 |  One   | {1000}
 2 |  Two   | {1000,4000}
 3 |  Three | {1000,4000,6000}

tab: ekwdesc
id | value  | desc
-----------------
 1 |  1000  | Max
 2 |  2000  | Tim
 3 |  3000  | Rita
 5 |  4000  | Sven
 6 |  5000  | Tom
 7 |  6000  | Bob

is it possible to select these columns and print the strings?

something like:

select name, ekw from test, ekwdesc

I would like to see this result:

id | name   | ekwdesc
-----------------
 1 |  One   | Max
 2 |  Two   | Max, Sven
 3 |  Three | Max, Sven, Bob

I tried with IN and ANY but couldn't get it to work.


回答1:


You had the right idea to use the any operator for the join. Once the join is complete, all that's left is to use string_agg to transform the result to the format you want:

SELECT   name, STRING_AGG(description, ', ')
FROM     test
JOIN     ekwdesc ON ekwdesc.value = ANY(test.ekw)
GROUP BY name

See the attached SQLFiddle for an executable example.



来源:https://stackoverflow.com/questions/30816763/postgresql-integer-array-value-join-to-integer-in-other-table-with-desc-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!