I am having a hard time dealing with query optimization and I believe the one am currently using can be improved a lot.
I have 4 tables;
Artist (14,930 rows)
| artist_id | artist_name | artist_slug | artist_country |
|---|---|---|---|
| 1 | Elle | elle | 5 |
Country (85 rows)
| country_id | country_name | country_slug |
|---|---|---|
| 1 | USA | usa |
Song (61,119 rows)
| song_id | song_title | song_artist_id | song_plays |
|---|---|---|---|
| 1 | Kitty kat | 1 | 38291 |
| 2 | Donkey | 1 | 8291 |
Lyrics (61,119 rows)
| lyrics_id | lyrics_song_id | lyrics_body |
|---|---|---|
| 1 | 1 | Kitty Kat lyrics |
| 2 | 2 | Donkey lyrics |
Am joining the tables using this query fetching a single artist's data plus, country, the total number of songs, the sum of the plays on all songs by the artist, and the total number of lyrics.
SELECT /*+ MAX_EXECUTION_TIME(2000) */
artist.*,
country.*,
COUNT(song.song_id) AS TotalSongs,
COUNT(lyrics.lyrics_id) AS TotalLyrics,
SUM(song.song_plays) AS TotalPlays
FROM artist
LEFT JOIN country ON artist.artist_country_id = country.country_id
LEFT JOIN song ON artist.artist_id = song.song_artist_id
LEFT JOIN lyrics ON song.song_id = lyrics.lyrics_song_id
WHERE artist_status = 'enabled' AND artist.artist_slug = '$slug'
GROUP BY artist.artist_id LIMIT 0, 1
How do I improve it to execute faster and use less resources?
Thanks in advance.
COUNT()results, where you might find you need correlated subqueries in theSELECTclause instead for some of those counts. That's likely to make things slower, but it could also be necessary if you want accurate results. For performance here, I'd start with your indexing.SongandLyricsinto a single table.ORDER BY, theLIMIT 1returns an unpredictable row.SHOW CREATE TABLEso we can determine what indexes are missing.