Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested SELECT statement with LEFT JOIN

I can't for the life of me figure out what's wrong with this SQL statement and why it's not producing any results. If I take out the LEFT JOIN is works, so what's wrong with it?

SELECT  b.id, r.avg_rating
FROM    items AS b
LEFT JOIN
(
    SELECT avg(rating) as avg_rating
    FROM ratings 
    GROUP BY item_id
) AS r 
  ON b.id = r.item_id
WHERE b.creator = " . $user_id . " 
AND b.active = 1
AND b.deleted = 0
ORDER BY b.order ASC, b.added DESC

Would appreciate the help greatly.

like image 881
Wasim Avatar asked Oct 19 '12 08:10

Wasim


People also ask

Can we use left join on subquery?

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 you use a join in a subquery?

Joins and subqueries are often used together in the same query. In many cases, you can solve a data retrieval problem by using a join, a subquery, or both.

How do I join two tables with left join in SQL?

Syntax For Left Join:SELECT column names FROM table1 LEFT JOIN table2 ON table1. matching_column = table2. matching_column; Note: For example, if you have a left table with 10 rows, you are guaranteed to have at least 10 rows after applying join operation on two tables.


1 Answers

add the item_id column in your subquery (I guarantee that it will work) so the ON clause can find r.item_id

SELECT item_id, avg(rating) as avg_rating
FROM ratings 
GROUP BY item_id
like image 90
John Woo Avatar answered Oct 01 '22 09:10

John Woo