json - Postgres JSON 加入、联合

标签 json postgresql

我有帖子、滑动、通知。我要

  1. 按得分对帖子排序
  2. 删除刷过的
  3. 加入通知与帖子并将加入的通知作为最高分

到目前为止,我已经完成了前两个,但无法将通知作为第一个元素添加到结果中。这是前两个的工作查询。

SELECT posts.id, posts.created_at, posts.data, ((posts.data)->>'score')::NUMERIC as score
FROM  posts
WHERE NOT EXISTS (
    SELECT  *
    FROM    swipes
    WHERE   ((swipes.data)->>'post_id')::INT = posts.id AND ((swipes.data)->>'user_id')::INT = 32)
ORDER BY (data)->>'score' 
LIMIT 5

我尝试使用 LEFT JOIN 添加通知,但无法成功。

SELECT posts.id, posts.created_at, posts.data, ((posts.data)->>'score')::NUMERIC as score
FROM  posts
WHERE NOT EXISTS (
    SELECT  *
    FROM    swipes
    WHERE   ((swipes.data)->>'post_id')::INT = posts.id AND ((swipes.data)->>'user_id')::INT = 32)

-- The part below is new
UNION  ALL
SELECT notifications.id, notifications.created_at, notifications.data, 9999999 AS score
FROM   notifications

--- THIS GIVES ERROR ---
LEFT   JOIN posts USING (notifications.data)->>'post_id') 

WHERE  ((notifications.data)->>'user_id')::INT = 32

-- After join order by score
ORDER BY score 
LIMIT 5

notifications 有一个名为 data 的列,类型为 jsonnotifications.data->post_id 应该由 posts.id 加入 9999999。其中 notifications.data->user_id 应该等于32.

最佳答案

如果除了表“posts”中的行之外还需要表“notifications”中的行,那么你应该UNION:

SELECT id, created_at, data, (data->>'score')::numeric AS score
FROM posts
WHERE NOT EXISTS (
    SELECT 1
    FROM swipes
    WHERE ((swipes.data)->>'post_id')::int = posts.id
      AND ((swipes.data)->>'user_id')::int = 32)

UNION  ALL

SELECT id, created_at, data, 9999999 AS score
FROM notifications
<strike>LEFT   JOIN posts USING (notifications.data)->>'post_id')</strike>
WHERE (data->>'user_id')::int = 32

-- After join order by score
ORDER BY score 
LIMIT 5;

如果您想将表“notifications”的列添加到表“posts”的列,那么您应该JOIN:

SELECT p.id, p.created_at, p.data, (p.data->>'score')::numeric AS score
       n.id, n.created_at, n.data 
FROM posts p
JOIN notifications n ON n->>'post_id' = p->>'post_id' -- guessing here
WHERE NOT EXISTS (
    SELECT 1
    FROM swipes
    WHERE ((swipes.data)->>'post_id')::int = p.id
      AND ((swipes.data)->>'user_id')::int = 32)
WHERE (n.data->>'user_id')::int = 32
ORDER BY score 
LIMIT 5;

关于json - Postgres JSON 加入、联合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31869010/

相关文章:

javascript - 在 jquery 中迭代 json

javascript - 使用以 '#' 字符开头的键读取 json 对象

c# - 如何在不丢失其特定属性的情况下将子实例反序列化为父对象?

macos - 在 osx-Lion 中创建并在 osx-snow-leopard 中访问的 postgres 9.1.3 数据的控制文件错误校验和不正确

SQL - 如何删除两个相互引用的实体

c# - 如何更新 JSON 字符串中的属性值?

javascript - Angular JSON 仅适用于本地 json 文件,不适用于 url

postgresql - Postgres 字符串与前导空格的比较

postgresql - 将 Kamailio 与 PostgreSQL 连接起来

SQL : 4 conditions combined with OR