Limiting a left join to returning one result?

前端 未结 5 1363
野性不改
野性不改 2021-02-19 21:29

I currently have this left join as part of a query:

LEFT JOIN movies t3 ON t1.movie_id = t3.movie_id AND t3.popularity = 0

The trouble is that

相关标签:
5条回答
  • 2021-02-19 21:39

    The error is clear -- you just need to create an alias for the subquery following its closing ) and use it in your ON clause since every table, derived or real, must have its own identifier. Then, you'll need to include movie_id in the subquery's select list to be able to join on it. Since the subquery already includes WHERE popularity = 0, you don't need to include it in the join's ON clause.

    LEFT JOIN (
      SELECT
        movie_id, 
        movie_name 
      FROM movies 
      WHERE popularity = 0
      ORDER BY movie_name
      LIMIT 1
    ) the_alias ON t1.movie_id = the_alias.movie_id
    

    If you are using one of these columns in the outer SELECT, reference it via the_alias.movie_name for example.

    Update after understanding the requirement better:

    To get one per group to join against, you can use an aggregate MAX() or MIN() on the movie_id and group it in the subquery. No subquery LIMIT is then necessary -- you'll receive the first movie_id per name withMIN() or the last with MAX().

    LEFT JOIN (
      SELECT
        movie_name,
        MIN(movie_id) AS movie_id
      FROM movies
      WHERE popularity = 0
      GROUP BY movie_name
    ) the_alias ON t1.movie_id = the_alias.movie_id
    
    0 讨论(0)
  • 2021-02-19 21:44

    you could try to add GROUP BY t3.movie_id to the first query

    0 讨论(0)
  • 2021-02-19 21:55
    LEFT JOIN movies as m ON m.id = (
        SELECT id FROM movies mm WHERE mm.movie_id = t1.movie_id
        ORDER BY mm.id DESC
        LIMIT 1    
    )
    
    0 讨论(0)
  • 2021-02-19 21:56

    Try this:

    LEFT JOIN 
        (
         SELECT t3.movie_name, t3.popularity   
         FROM movies t3 WHERE t3.popularity = 0 LIMIT 1
        ) XX
         ON  t1.movie_id = XX.movie_id AND XX.popularity = 0
    
    0 讨论(0)
  • 2021-02-19 22:00

    MySQL 5.7+ allows you to use ANY_VALUE. you didn't provide the full query so i'll have to guess using xxx

    SELECT xxx.id,ANY_VALUE(m.movie_name) movie_name, ANY_VALUE(popularity) popularity
    FROM xxx
    LEFT JOIN movies m ON (m.movie_name=xxx.movie_name AND popularity=0)
    GROUP BY xxx.id
    

    more info https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html

    0 讨论(0)
提交回复
热议问题