I have a query that uses a lot of aggregate functions to build data for each item (a photo album). This data is critical and needs to be there. Currently the query alone takes about 1.5 seconds to execute, which is just too long.
I have created these functions because there are quite a few queries that all need to do these calculations, so it made sense to separate them into their own functions for ease of code maintainability. Otherwise, everytime a condition changes, there would be 5 or more places to go and look in to make the changes.
I would really like to know what I can do to make this query faster. It's clear the aggregate functions are the culprit because if I replace them with a simple SELECT * it runs in about 0.1 seconds.
The only thing I can think of is removing the aggregate functions and doing inner joins / subqueries for each item that needs to be aggregated. As you can imagine, I would really like to NOT do this as it would require refactoring to loads of other places and make the code maintenance extremely messy.
Any suggestions? Thanks!
SELECT
fnAlbumGetNumberOfPhotos(albumId,1,0, 100) AS albumNumberOfPhotos,
fnLikeGetCount(1, 3, album.albumId) AS albumLikeCount,
fnGetAlbumPhotoViewCount(albumId) AS albumNumberOfPhotoViews,
fnLikeGetDoesUserLikeDislike(1, 3, album.albumId, 100) AS albumDoesUserLike,
fnObjectTagGetObjectTags(3, albumId) AS albumTags
FROM
album
WHERE 0 = 0
-- AND insert additional filters here
LIMIT 0,15
The functions are all simple aggregate functions, e.g:
CREATE DEFINER=`root`@`%` FUNCTION `fnAlbumGetNumberOfPhotos`(_albumId int, _photoIsActive tinyint, _photoIsDisabled tinyint, _userId int) RETURNS int(11)
BEGIN
DECLARE outNumberOfPhotos int DEFAULT 0;
DECLARE _userRoleId int DEFAULT 0;
SET _userRoleId = (SELECT userRoleId FROM user WHERE userId = _userId);
SET outNumberOfPhotos =
(
SELECT COUNT(*) AS outNumberOfPhotos
FROM photo
WHERE photoAlbumId =开发者_开发百科 _albumId
AND photoIsDisabled = _photoIsDisabled
AND photoIsActive = _photoIsActive
AND (photoPublishDate <= Now() || photoCSI = _userId || _userRoleId = 2)
);
RETURN outNumberOfPhotos;
END $$
When sql optimizer build execution plan for any query it splits query into singular operations and then manipulate with them. Unfortunately Function is a "black box" for sql optimizer - it doesn't know what inside that function and assumes function call as a singular operation. If performance is critical for your query:
- recheck your indexes on tables
- INLINE your functions calls - in this case query optimizer can build an optimal execution plan base on your indexes
- instead of p.2 you can use VIEWs (of course if it's possible) - they are transparent for optimizer.
Hope this help
精彩评论