Skip to content

Instantly share code, notes, and snippets.

@handuy
Created June 7, 2018 10:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save handuy/f233e1153908e337b643b250453d109c to your computer and use it in GitHub Desktop.
Save handuy/f233e1153908e337b643b250453d109c to your computer and use it in GitHub Desktop.
Từ một mảng các tag id lấy ra thông tin chi tiết từng phẩn tử tag
Bảng posts có cột tag_ids là một mảng các id link đến bảng tag
Với 1 mảng tag có id là [1,2,3], cần lấy ra một mảng các thông tin cụ thể của từng tag id
Cách 1:
SELECT temp_post.Id, temp_post.author_name, temp_post.avatar, temp_post.title,
json_agg(temp_tag.detail) AS tag
FROM
(
SELECT posts.Id AS Id, users.full_name AS author_name, users.avatar AS avatar, posts.title AS title, posts.tag_ids AS tag_ids
FROM posts, users
WHERE posts.author_id = users.id
AND posts.status = 1
ORDER BY published_at DESC
-- LIMIT ?
-- OFFSET ?
) temp_post
LEFT JOIN
(
SELECT row_to_json(temp) AS detail
FROM (
select id, title, slug
from tags
) temp
) temp_tag
ON temp_tag.detail ->> 'id' = ANY(temp_post.tag_ids)
GROUP BY temp_post.Id, temp_post.author_name, temp_post.avatar, temp_post.title
Cách này chạy mất 246 milliseconds
Cách 2:
SELECT posts.id, posts.title, posts.tag_ids, users.full_name,
(
select json_agg(row_to_json(d))
from (
select id, title
from tags
where tags.id = ANY(posts.tag_ids)
) d
) AS tagdetails
FROM posts, users
Where posts.author_id = users.id
AND posts.status = 1
Cách này chạy mất 132 milliseconds
C
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment