我有两张桌子。这是一个简化的细分:
Table #1 - Album:
Rows:
albumId | title | userId
Table #2 - Photo:
Rows:
photoId | src | albumId
我想从每张专辑中获取第一张照片的src。这显然不是我想要的,但这就是我所拥有的:
SELECT pa.id, pa.title, p.src
FROM Album pa
LEFT JOIN Photo p ON pa.Id = p.albumId
WHERE pa.userId = 1
返回用户的所有照片。我希望这些结果中每张专辑的第一个结果。
答案 0 :(得分:3)
我认为你可能想要添加一个cover_photo_id,就像@zerkms所说的那样,但是这可以解决问题(不知道使用子查询是否足以满足您的需求)
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
答案 1 :(得分: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;
答案 2 :(得分:-1)
您想使用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
如果您确实想要相当于FIRST,请参阅this answer
答案 3 :(得分:-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