My question is a performance question.
Given this postgresql, I get this result.
select fp.fp_id post_id,
tag_linking_table.sehset_tid hashtag
FROM soc_ent social_entity
JOIN fp on fp.fp_id = social_entity.se_id
LEFT JOIN sehset tag_linking_table on tag_linking_table.sehset_seid = social_entity.se_id
GROUP BY post_id, hashtag
I can see that the post ending in 89 has 2 hashtags. All good so far.
I now modify the query to get the following expected result.
select fp.fp_id post_id,
jsonb_agg(tag_linking_table.sehset_tid) hashtag
FROM soc_ent social_entity
JOIN fp on fp.fp_id = social_entity.se_id
LEFT JOIN sehset tag_linking_table on tag_linking_table.sehset_seid = social_entity.se_id
GROUP BY post_id
All good so far. My hashtags are properly grouped. Now if i changed the query to get the likes count using the same method above, this is my expected result
select fp.fp_id post_id,
count(social_entity_likes.se_likes_ca) likes
FROM soc_ent social_entity
JOIN fp on fp.fp_id = social_entity.se_id
LEFT JOIN se_likes social_entity_likes on social_entity.se_id = social_entity_likes.se_likes_seid
GROUP BY post_id
So in summary, my post ending in 89 has 2 likes from the Likes linking table, and 2 Hashtags from the hashtag linking table.
Now comes the problem. I want to display the hashtags and the likes in one sql query, so i modified the sql to the following.
select fp.fp_id post_id,
jsonb_agg(tag_linking_table.sehset_tid) hashtag,
count(social_entity_likes.se_likes_ca) likes
FROM soc_ent social_entity
JOIN fp on fp.fp_id = social_entity.se_id
LEFT JOIN sehset tag_linking_table on tag_linking_table.sehset_seid = social_entity.se_id
LEFT JOIN se_likes social_entity_likes on social_entity.se_id = social_entity_likes.se_likes_seid
GROUP BY post_id
But oddly, my result was this:
The solution I found was to add the word distinct inside the aggregation function which gave me the correct results.
select fp.fp_id post_id,
jsonb_agg(distinct tag_linking_table.sehset_tid) hashtag,
count(distinct social_entity_likes.se_likes_ca) likes
FROM soc_ent social_entity
JOIN fp on fp.fp_id = social_entity.se_id
LEFT JOIN sehset tag_linking_table on tag_linking_table.sehset_seid = social_entity.se_id
LEFT JOIN se_likes social_entity_likes on social_entity.se_id = social_entity_likes.se_likes_seid
GROUP BY post_id
But I am told every where that distinct will degrade the performance (and especially since i will have very large tables).
Question: What caused my duplicate problem? and is distinct the correct way to fix it? And if so how can I get the same result without using the distinct keyword? Thanks.




