Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using subselect to accomplish LEFT JOIN

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.

like image 314
Andre Avatar asked Mar 17 '10 23:03

Andre


People also ask

Can we use subquery in left join?

Move the 'Reserve' table named in the subquery to the FROM clause and join it to 'Customers' using LEFT JOIN. The WHERE clause compares the customer_id column to the ids returned from the subquery. Hence convert the IN expression to an explicit direct comparison between id columns of two tables in the FROM clause.

Can we use subquery in joins?

Subqueries can be used as an alternative to joins. A subquery is typically nested inside the WHERE clause. Subqueries must always be enclosed within parentheses. The table that's specified in the subquery is typically different than the one in the outer query, but it can be the same.

Is subquery faster than LEFT join?

Advantages Of Joins: The advantage of a join includes that it executes faster. The retrieval time of the query using joins almost always will be faster than that of a subquery. By using joins, you can maximize the calculation burden on the database i.e., instead of multiple queries using one join query.

IS LEFT join better than subquery?

A LEFT [OUTER] JOIN can be faster than an equivalent subquery because the server might be able to optimize it better—a fact that is not specific to MySQL Server alone. So subqueries can be slower than LEFT [OUTER] JOIN , but in my opinion their strength is slightly higher readability.


2 Answers

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
like image 117
mechanical_meat Avatar answered Oct 08 '22 06:10

mechanical_meat


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.

like image 42
MisterZimbu Avatar answered Oct 08 '22 06:10

MisterZimbu