6

I have two tables. Here is a simplified breakdown:

Table #1 - Album:
Rows:
albumId | title | userId

Table #2 - Photo:
Rows:
photoId | src | albumId

I want to get the first photo's src from each album. This is pretty clearly not what I'm looking for but here is what I have:

SELECT pa.id, pa.title, p.src
FROM Album pa
LEFT JOIN Photo p ON pa.Id = p.albumId
WHERE pa.userId = 1

That returns all of the photos from the user. I would like the first result for each album in those results.

kamchatka
  • 127
  • 2
  • 2
  • 6

4 Answers4

3

I think you may want to add a cover_photo_id, as @zerkms said, but this could do the trick (don't know if using subqueries is efficient enough for your situation)

SELECT pa.albumId, pa.title, p.src
FROM Album pa
LEFT JOIN Photo p 
  ON p.photoId = (SELECT MIN(photoId) FROM Photo WHERE albumId = pa.albumId)
WHERE pa.userId = 1
g3rv4
  • 19,750
  • 4
  • 36
  • 58
0
SELECT pa.id, pa.title, p.src
FROM Album pa
  LEFT JOIN Photo p ON pa.Id = p.albumId
WHERE pa.userId = 1 LIMIT 1;
kba
  • 19,333
  • 5
  • 62
  • 89
-1

You want to use GROUP BY

SELECT pa.id, pa.title, p.src
FROM Album pa
LEFT JOIN Photo p ON pa.Id = p.albumId
WHERE pa.userId = 1
GROUP BY pa.id, pa.title

If you actually want the equivalent of a FIRST, see this answer

Community
  • 1
  • 1
pocketfullofcheese
  • 8,427
  • 9
  • 41
  • 57
-2
SELECT pa.id, pa.title, p.src
FROM Album pa
LEFT JOIN Photo p ON pa.Id = p.albumId
WHERE pa.userId = 1
GROUP BY pa.albumId
ORDER BY p.photoID
Ata S.
  • 890
  • 7
  • 12
  • you can't get fields that aren't aggregates or that are on the group key... can you? – g3rv4 Apr 10 '12 at 00:05
  • 2
    @elgerva: Actually you can in MySQL, but the returned data (for `p.src`) is undefined. It can be from any (random) row in the group. – ypercubeᵀᴹ Apr 10 '12 at 00:07
  • Yep you can in MySQL. MySQL shouldn't do that I agree. I don't know if it is always the expected row, I just checked a few results and it is fine. Seems like working to me. – Ata S. Apr 10 '12 at 00:15