Appreciate this is a simple use case but having difficulty doing a join in Postgres using an array.
I have two tables:
table: shares
id | likes_id_array timestamp share_site
-----------------+-----------------+----------+-----------
12345_6789 | [xxx, yyy , zzz]| date1 | fb
abcde_wxyz | [vbd, fka, fhx] | date2 | tw
table: likes
likes_id | name | location
--------+-------+----------+-----
xxx | aaaa | nice
fpg | bbbb | dfpb
yyy | mmmm | place
dhf | cccc | fiwk
zzz | dddd | here
desired - a result set based on shares.id = 12345_6789:
likes_id | name | location | timestamp
--------+-------+----------+------------+-----------
xxx | aaaa | nice | date1
yyy | mmmm | place | date1
zzz | dddd | here | date1
the first step is using unnest() for the likes_id_array:
SELECT unnest(likes_id_array) as i FROM shares
WHERE id = '12345_6789'
but I can’t figure out how to join the results set this produces, with the likes table on likes_id. Any help would be much appreciated!
4
Answers
You can create a
CTE
with your query with the likes identifiers, and then make a regular inner join with the table of likesDemo
You can use
ANY
:You could do this with subqueries or a CTE, but the easiest way is to call the
unnest
function not in theSELECT
clause but as a table expression in theFROM
clause:You can use
jsonb_array_elements_text
with a (implicit) lateral join:Output:
Or if you want to make the lateral join explicit (notice the addition of the
LATERAL
keyword):