I have the following MySQL code:
Working Query
SELECT name, AVG(q1) AS avg
FROM respondents
LEFT JOIN results_new ON respondents.login_id = results_new.company
WHERE respondents.brand = 'ABC'
AND results_new.sdate = 'MAY2014'
GROUP BY name
ORDER BY avg
DESC
The above works correctly, it brings back 35 rows and displays the name and average correctly.
Non working query
SELECT name, AVG(q1) AS avg
FROM respondents
LEFT JOIN results_new ON respondents.login_id = results_new.company
WHERE respondents.brand = 'ABC'
AND results_new.sdate = 'NOV2014'
GROUP BY name
ORDER BY avg
DESC
The above returns zero
results - which is correct as there is no data in the table for `NOV2014'.
However, what I expected to happen was the query to return 35 rows with the name
and NULL
next to each name. Clearly I think my JOIN
is incorrect but I cannot work out where I am going wrong.
Any and all advice welcomed.
Your where
clause turns your left join
into an inner join
since you filter on data in the joined table. Put this condition in the on
clause of your join.
SELECT name, AVG(q1) AS avg
FROM respondents
LEFT JOIN results_new ON respondents.login_id = results_new.company
AND results_new.sdate = 'NOV2014'
WHERE respondents.brand = 'ABC'
GROUP BY hotel_name
ORDER BY avg DESC
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.