Firstly, you have an id of no voice, and then make a left join in the from list and, finally, the amount in stock. It clogs your voice three times. If each vote is possibly associated with one “ItemID”, then it would be best to pre-aggregate on its own, since its own “amount” was made ONCE.
In addition, since your final “HAVING” sentence is the direct basis of the votes, having a left voice connection becomes dead and eventually ends with a regular JOIN.
All that was said, I would first request FIRST for those votes that FINISH with the qualification condition HAVING in front, then join the content elements and other associations ... The request with User_Favorites is a counter and will be either 0 (not found) or 1 ( found). Should not be necessary in case / when
My first query alias "PQ" represents "PreQuery"
SELECT PQ.ItemID, PQ.VSum as Votes, PQ.HasVoted, i.pending, i.itemid, i.message, i.cid, i.dateadded, i.entrypoint, i.userid, c.name AS cname, c.tag AS ctag, ( SELECT COUNT(commentid) FROM `comments` WHERE comments.itemid = PQ.itemid) AS commentcount, ( SELECT COUNT(*) FROM user_favorites uf WHERE uf.itemid = PQ.itemid AND uf.userid = @userid ) AS isFavorite from ( SELECT v.itemid, SUM( case when v.Direction = 1 then 1 when v.Direction = 2 then -1 ELSE 0 end ) as VSum, MAX( if( votes.userid = @userid, 1, 0 ) AS HasVoted from votes v group by v.itemid having VSum > -3 ) PQ JOIN ContentItems i ON PQ.ItemID = i.ItemID and i.Pending = 0 JOIN Categories c ON i.cid = c.cid ORDER BY i.dateadded DESC
Others pointed to the need for indices agreed upon. I would make sure that each table has a corresponding index on the user ID or product identifier (or where necessary).
A couple of other points ... Initially, you run a query requesting all ContentItems, but leaving a vote ... But then applying the user ID element. It DEFINITELY smells like a request for a specific user. At the same time, I MUST pre-run the entire request by selecting only the ItemID with which the user identifier did something with ... THEN continue the request.