Я пытаюсь повысить производительность этого запроса. Когда я удаляю ORDER BY
, он запускается менее чем за секунду, а когда я снова добавляю его, это занимает более 30 секунд. Просто интересно, чем я могу помочь? Я знаю, что могу добавить индексы, но я не уверен, какие из них добавить, потому что это подзапрос.
SELECT
account.full_name AS full_name,
account.account_status AS account_status,
username.username AS username,
profile_image.s3_key AS profile_image_s3_key,
profile_image.image_id AS profile_image_id,
COALESCE(
(
SELECT count(*)
FROM (
SELECT following.followee_account_id, image.s3_key, image.image_id
FROM following, ranked_list_ranked_list_item_map, image, account, ranked_list
WHERE (
following.follower_account_id = 5 OR
ranked_list.owner_account_id = 5
)
AND following.followee_account_id = ranked_list.owner_account_id
AND ranked_list_ranked_list_item_map.ranked_list_item_id = ranked_list_item__ranked_list_item_id
AND ranked_list_ranked_list_item_map.ranked_list_id = ranked_list.ranked_list_id
AND ranked_list_ranked_list_item_map.is_pending = 'false'
AND account.account_id = ranked_list.owner_account_id
AND account.profile_image_id = image.image_id
AND status = 'active'
AND ranked_list.visibility = 'world'
GROUP BY following.followee_account_id, image.s3_key, image.image_id
) as follower_data
), 0
) as num_foll
FROM ranked_list_item
INNER JOIN ranked_list_item_with_details ON ranked_list_item.ranked_list_item_id = ranked_list_item_with_details.ranked_list_item__ranked_list_item_id
LEFT JOIN account ON account.account_id = ranked_list_item.owner_account_id
LEFT JOIN image profile_image ON account.profile_image_id = profile_image.image_id
LEFT JOIN username ON account.account_id = username.account_id
WHERE (
owner_account_id IS NULL OR
owner_account_id = 5
)
AND (
TRUE = TRUE
OR ranked_list_item.ranked_list_item_id = ANY ('{}')
)
AND ranked_list_item.type = ANY('{"music_track_from_apple_music","music_track_manually_entered","restaurant_user_made","restaurant_manually_entered","book_from_open_library","book_manually_entered","wine_from_livex","wine_manually_entered","location_user_made","location_manually_entered","entertainment_manually_entered","entertainment_from_tmdb","joke_manually_entered","sport_related_manually_entered","other_manually_entered"}')
AND NOT EXISTS (
SELECT true
FROM ranked_list_item_flag
WHERE flagger_account_id = 5
AND ranked_list_item_id = ranked_list_item.ranked_list_item_id
)
ORDER BY num_foll DESC