The biggest efficiency killer here is the correlated subqueries:
(SELECT CONCAT(name, " ", surname)
FROM pt_users us
WHERE us.uID = ph.uID) name_surname
... and:
ifnull((SELECT SUM(vote)
FROM pt_votes vo
WHERE vo.pID = ph.pID),0) points,
Each of these will run once for every row that makes it past the WHERE
clause.
To eliminate the correlated subqueries you need to join to the pt_votes
and pt_users
tables. Also, because you're summing votes you'll need to GROUP BY
, which means you really need to get rid of that SELECT *
as was already recommended in the comments.
The query will look something like this. When you determine which pt_photos
columns you need be sure to add them to the GROUP BY
list:
SELECT
pt_photos.pID,
pt_photos.uID,
pt_photos.this,
pt_photos.that,
CONCAT(pt_users.name, ' ', pt_users.surname) AS name_surname,
IFNULL(SUM(pt_votes.vote), 0) AS points
FROM pt_photos
JOIN pt_users ON pt_photos.uID = pt_users.uID
LEFT JOIN pt_votes ON pt_photos.pID = pt_votes.pID
WHERE 1
GROUP BY
pt_photos.pID,
pt_photos.uID,
pt_photos.this,
pt_photos.that
And if your query really has a WHERE 1
clause you can drop it.