Link to home
Start Free TrialLog in
Avatar of rovermedia
rovermediaFlag for Afghanistan

asked on

Help with SQL Syntax

Hoping someone can help with a photo gallery migration...I'm not really proficient with SQL, but am 99% done.

I have two tables, PHOTOS and PHOTOS_ALBUMS

PHOTOS is essentially all the pictures in the gallery (id), along with id of the uploader (creator), and what Album those pictures belong to (albumid).

ALBUMS is all the albums (id), the user that created it (creator), and what Photo should be set as the thumbnail for the album (photoid)

I want to set the thumbnail for all the albums.  Some users have multiple albums.  I want the thumbnail to be the last photo they uploaded to each album.

So I need a query that will

A) Go through PHOTOS and select the last id from each albumid
B) In ALBUMS set photoid for each album to the last id selected above

Here are some sample tables:

PHOTOS

ID = 1
ALBUMID = 26
CREATOR = 9647
FILE: imagepath/81729.jpg

ID = 2
ALBUMID = 26
CREATOR = 9647
FILE: imagepath/0458435.jpg

ID = 3
ALBUMID = 35
CREATOR = 9647
FILE: imagepath/7347328974.jpg


ALBUMS

ID = 26
CREATOR = 9647
PHOTOID =

So in the example above, I'd want to populate alumbs.photoid with the last photos.id (in this case, 2).  Of course I have 100,000 users and 250,000 albums to do this for.

I know I could be clearer, but it's 3:30 AM here and my mind is fried...even I can barely make sense of what I am writing at this hour!
Avatar of isaackhazi
isaackhazi

Are you using any API or directly wanna do it in SQL?

I could give you a solution in .NET if you want.
a) SELEXT MAX(ID) FROM ALBUMS GROUP BY ALBUMID
@brandscape: rovermedia wants to update all the albums with the last uploaded photo ID not just select em.
I would suggest using an update based on a select using table alises, something like this

update albums
set albums.photoid = max(sel.id)
from photos sel
group by sel.albumid
where albums.albumid = sel.albumid
sorry - my first post was to answer part A) but should read :

a) SELEXT MAX(ID) FROM PHOTOS GROUP BY ALBUMID

IT's usefull to see the answer to B) in context of the answer to A)
SELECT MAX(ID) FROM PHOTOS GROUP BY ALBUMID
ASKER CERTIFIED SOLUTION
Avatar of Bill Prew
Bill Prew

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
What dbms are you using?
Supposing you work with Microsoft SQL Server, the statement could be :

UPDATE Albums SET PHOTOID = b.maxid from
Albums a INNER JOIN (SELECT AlbumID , Max(ID) maxid FROM Photos group by AlbumID) b  
ON a.ID = b.ALBUMID

Open in new window