Created
June 7, 2018 10:37
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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