Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 512
matzeihnsein Avatar asked Jun 13 '15 08:06

matzeihnsein


1 Answers

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.

like image 95
Mureinik Avatar answered Oct 09 '22 09:10

Mureinik