I need help in a mysql query, here are the details:
Three Tables, Album_Master , Album_Photo_Map, Photo_Details
Album_Master Table Structure
album_id(P) | album_name | user_id(F)
1 abc 1
2 xyz 1
3 pqr 1
4 e3e 2
Album_Photo_Map Table Structure
auto_id(P) | album_id(F) | photo_id
1 1 123
2 1 124
3 2 123
4 2 125
5 1 127
6 3 127
Photo_Details Table Structure
auto_id(P) | image_id(F) | image_url
1 123 http....
2 124 http....
3 125 http...
I want to write a query to get the album name with image url for user_id 1
The output I am expecting here is
album_id | album_name | image_url
1 abc http.. (either 123 or 124 or 127 - only one url)
2 xyz http.. (either 123 or 125 - only one)
3 pqr http.. (127 only)
The query I am using is taking too much time to execute, almost 8s.
SELECT A.album_id
, A.album_name
, D.image_url
from Album_Master A
, Album_Photo_Map E
LEFT
JOIN Photo_Details D
ON (D.image_id = (
SELECT P.photo_id
FROM Album_Photo_Map P
, Photo_Details Q
WHERE P.photo_id = Q.image_id
AND P.album_id = E.album_id limit 0,1)
)
WHERE A.album_id = E.album_id
AND A.user_id = 1
group
by A.album_id
, E.album_id
, D.image_url;
I am looking for an optimize version of the query, any help will be really appreciated. If I use image_url
in group by it is creating multiple records, also if I remove D.image_url
it gives me error
D.image_url' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
Note: user can assign one photo in multiple albums, result should pick only one photo per album, there might be 100 of photos in an album.
See Question&Answers more detail:
os