MySQL return first row of a joined table

前端 未结 5 610
庸人自扰
庸人自扰 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:39

    Many databases have some equivalent of "select top 10 * from...". In mySql, the syntax would be "select * from ... limit 10".

    ... BUT ...

    In this case, uou really want "group by" and "max()"!

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2021-01-04 13:58
    SELECT c.*, d.*
    FROM country c 
      INNER JOIN ducks d 
        ON d.id =                         --- guessing the ducks Primary Key here
           ( SELECT dd.id                 --- and here  
             FROM ducks dd
             WHERE c.id = dd.country_id
             ORDER BY dd.rating DESC
             LIMIT 1
           )
    

    An index on (country_id, rating, id) for MyISAM table or (country_id, rating) for InnoDB table, would help.

    This query will show only one duck per country, even with more than one having the same rating. If you want ducks with tied rating to appear, use @imm's GROUP BY answer.

    0 讨论(0)
  • 2021-01-04 13:58

    Try this:

    SELECT c.country, MAX(d.rating) AS max_rating
    FROM country c
    JOIN ducks d ON c.id = d.country_id
    GROUP BY c.id
    ORDER BY c.country ASC
    

    If the "highest rating" is 1, then change MAX(d.rating) to MIN(d.rating)

    0 讨论(0)
  • 2021-01-04 14:03

    You could try just adding a selecting join, for

    SELECT c.*, d.*
    FROM country c 
    INNER JOIN ducks d ON c.id = d.country_id
    LEFT JOIN ducks d2 ON d.country_id = d2.country_id AND d2.rating > d.rating
    WHERE d2.id IS NULL
    
    0 讨论(0)
提交回复
热议问题