Using subselect to accomplish LEFT JOIN

65,831

Solution 1

A subselect can only have one column returned from it, so you would need one subselect for each column that you would want returned from the model table.

Solution 2

There are many practical uses for what you suggest.

This hypothetical query would return the most recent release_date (contrived example) for any make with at least one release_date, and null for any make with no release_date:

SELECT m.make_name, 
       sub.max_release_date
  FROM make m
       LEFT JOIN 
           (SELECT id, 
                   max(release_date) as max_release_date
              FROM make 
           GROUP BY 1) sub
       ON sub.id = m.id
Share:
65,831

Related videos on Youtube

Andre
Author by

Andre

Updated on March 18, 2020

Comments

  • Andre
    Andre about 4 years

    Is is possible to accomplish the equivalent of a LEFT JOIN with subselect where multiple columns are required. Here's what I mean.

    SELECT m.*, (SELECT * FROM model WHERE id = m.id LIMIT 1) AS models FROM make m
    

    As it stands now doing this gives me a 'Operand should contain 1 column(s)' error.

    Yes I know this is possible with LEFT JOIN, but I was told it was possible with subselect to I'm curious as to how it's done.

  • Andre
    Andre about 14 years
    I can indeed return multiple columns in a subselect albeit not in the way I want. This query returns multiple columns. SELECT m.*, models.* FROM make m, (SELECT * FROM model LIMIT 1) AS models
  • MisterZimbu
    MisterZimbu about 14 years
    Subqueries can return more than one column from FROMs and JOINs, since you're working with rows in that context. Since you're only working with scalars in the SELECT context you can only return one value from a subquery there.

Related