**Table parent**
parentId | name
**Table children**
childId | parentId | pictureId | age
**Table childrenPictures**
pictureId | imgUrl
no i would like to return all parent names with their eldest son’s picture (only return parents that have children, and only consider children that have pictures)
so i thought of something like :
SELECT c.childId AS childId,
p.name AS parentName,
cp.imgUrl AS imgUrl,
MAX(c.age) AS age
FROM parent AS p
RIGHT JOIN children AS c ON (p.parentId = c.parentId)
RIGHT JOIN childrenPictures AS cp ON (c.pictureId = cp.pictureId))
GROUP BY p.name
This query will return each parent’s eldest son’s age, but the childId will not correspond to the eldest sons id, so the output does not show the right sons picture.
you need to pre-query per family to get the age of the oldest child that has an image, then get parent’s name / image information… something like…
The inner query is prequalifying just by parent, childs highest age that an image exists… So, if you have a family with 3 children, oldest has no picture, 2nd oldes DOES, the the 2nd oldest is the one that will show in the above query. Additionally, what do you want to do if a family has twins, and BOTH have pictures on file. This query would show BOTH children if age is based on actual integer representation. However, if age is computed based on date arithmetic and would be more accurate… Ex: one child born Jan 1 of year X, and within the same year, another child born Dec 1…. As of December, they would be the same integer based age, but one obviously 11 months older than the other.
Additionally, if you want the oldest REGARDLESS of having a picture, the above query would have to be changed only slightly… let me know if this is what you are looking for.