在Postgres中使用UNNEST加入

jutyujz0  于 2022-10-15  发布在  PostgreSQL
关注(0)|答案(4)|浏览(201)

这是一个简单的用例,但是很难使用数组在postgres中进行联接。
我有两张table:

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

第一步是对like_id_array使用unnest():

SELECT unnest(likes_id_array) as i FROM shares
WHERE id = '12345_6789'

但是我不知道如何将这个结果集与Like_id上的Like表结合起来。任何帮助都将不胜感激!

jei2mxaa

jei2mxaa1#

您可以使用Like标识符用查询创建一个CTE,然后与Like表进行常规的内部连接

with like_ids as (
  select
      unnest(likes_id_array) as like_id
  from shares
     where id = '12345_6789'
) 
select
    likes_id,
    name,
    location
from likes 
   inner join like_ids
on likes.likes_id = like_ids.like_id

Demo

jdzmm42g

jdzmm42g2#

您可以使用ANY

SELECT a.*, b.timestamp FROM likes a JOIN shares b ON a.likes_id = ANY(b.likes_id_array) WHERE id = '12345_6789';
e5njpo68

e5njpo683#

您可以使用子查询或CTE来执行此操作,但最简单的方法是不在SELECT子句中调用unnest函数,而是在FROM子句中将其作为表表达式调用:

SELECT likes.*, shares.timestamp
FROM shares, unnest(likes_id_array) as arr(likes_id)
JOIN likes USING (likes_id)
WHERE shares.id = '12345_6789'
svujldwt

svujldwt4#

可以将jsonb_array_elements_text与(隐式)lateral join一起使用:

SELECT
  likes.likes_id,
  likes.name,
  likes.location,
  shares.timestamp
FROM
  shares,
  jsonb_array_elements_text(shares.likes_id_array) AS share_likes(id),
  likes
WHERE
  likes.likes_id = share_likes.id AND
  shares.id = '12345_6789';

产出:

┌──────────┬──────┬──────────┬─────────────────────┐
│ likes_id │ name │ location │      timestamp      │
├──────────┼──────┼──────────┼─────────────────────┤
│ xxx      │ aaaa │ nice     │ 2022-10-12 11:32:39 │
│ yyy      │ mmmm │ place    │ 2022-10-12 11:32:39 │
│ zzz      │ dddd │ here     │ 2022-10-12 11:32:39 │
└──────────┴──────┴──────────┴─────────────────────┘
(3 rows)

或者,如果要使横向联接显式(请注意添加了关键字LATERAL):

SELECT
  likes.likes_id,
  likes.name,
  likes.location,
  shares.timestamp
FROM
  shares,
  LATERAL jsonb_array_elements_text(shares.likes_id_array) AS share_likes(id),
  likes
WHERE
  likes.likes_id = share_likes.id AND
  shares.id = '12345_6789';

相关问题