Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql - How can I get the first result from a subquery?

Tags:

sql

mysql

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.

like image 360
kamchatka Avatar asked Apr 09 '12 23:04

kamchatka


People also ask

How do I get the first record in MySQL?

To get the first row use LIMIT 1 . To get the 2nd row you can use limit with an offset: LIMIT 1, 1 . To get the last row invert the order (change ASC to DESC or vice versa) then use LIMIT 1 .

Can you have ORDER BY in subquery?

An ORDER BY command cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY command can be used to perform the same function as the ORDER BY in a subquery.


1 Answers

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
like image 166
g3rv4 Avatar answered Oct 16 '22 13:10

g3rv4