patternsqlMinor
Song database query
Viewed 0 times
databasesongquery
Problem
I am relatively inexperienced with MySQL and have a query, which to my eyes appears relatively complex:
Essentially, this query collects data from several different tables about a list of songs:
I am specifically concerned about the fact that I am currently dynamically generating the
SELECT SQL_CALC_FOUND_ROWS
songsID, song_name, artist_band_name, author, song_artwork, song_file,
genre, song_description, uploaded_time, emotion, tempo,
user, happiness, instruments, similar_artists, play_count,
projects_count,
rating, ratings_count, waveform, datasize, display_name, user_url, genre_id,
IF(user_ratings_count, 'User Voted', 'Not Voted') as voted
FROM (
SELECT
sp.songsID, projects_count,
AVG(rating) as rating,
COUNT(rating) AS ratings_count,
COUNT(IF(userid=$userid, 1, NULL)) as user_ratings_count
FROM (
SELECT songsID, COUNT(*) as projects_count
FROM $sTable s
LEFT JOIN $sTable2 p ON s.songsID = p.songs_id
GROUP BY songsID) as sp
LEFT JOIN $sTable3 r ON sp.songsID = r.songid
GROUP BY sp.songsID) as spr
JOIN $sTable s USING (songsID)
LEFT JOIN $sTable5 q ON s.user = q.ID
LEFT JOIN (
SELECT g.song_id, GROUP_CONCAT(g.genre_id SEPARATOR ',') as genre_id
FROM $sTable6 g
JOIN $sTable h ON h.songsID = g.song_id
GROUP by h.songsID) as gs
ON s.songsID = gs.song_idEssentially, this query collects data from several different tables about a list of songs:
- The song table itself is
$sTablewith the other tables containing various related information such as ratings, projects, uploaded user information etc.
- The final part of the query collects a comma-separated list of
genre_ids from$sTable6.
- The
WHEREclause is dynamically generated depending on what the user is filtering upon.
I am specifically concerned about the fact that I am currently dynamically generating the
WHERE clause when a user wants to search by genre_id, by looping through a string ofSolution
I don't know is it help or not (since it's a really complicated query) but it's usually worth caching computed values such as
rating and ratings_count and updating them once a day or an hour for example. In the majority of the cases it's enough to provide non-real-time data to the users.Context
StackExchange Code Review Q#8359, answer score: 2
Revisions (0)
No revisions yet.