MySQL return first row of a joined table

前端 未结 5 612
庸人自扰
庸人自扰 2021-01-04 13:19

I have two tables (country & ducks) where the country table has every country in the world and the ducks table has a list of ducks with a country_id field to link to the

5条回答
  •  北荒
    北荒 (楼主)
    2021-01-04 13:49

    You might try:

    SELECT c.*, d.*
    FROM country c
    INNER JOIN (
        SELECT d.country_id, d.id, MAX(d.rating) AS rating
        FROM ducks d
        GROUP BY d.country_id
    ) q ON (q.country_id = c.id)
    
    INNER JOIN ducks d 
        ON (d.country_id, d.rating) = (q.country_id, q.rating)
    

提交回复
热议问题