Limiting a left join to returning one result?

前端 未结 5 1269
野性不改
野性不改 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
    

提交回复
热议问题