Question

This SQL query is only returning one result, when it should return many. I'm using SQL JOIN to combine data from two tables into one query. I'm trying to select those rows in table s that contain a search word (Why I'm using SQL LIKE) and then pull data (as a rounded average) from table r whose column 'avrank' matches the column 'id' from table s. Any suggestions on what I could change so that more than one result will return?

          SELECT s.*, 
          ROUND(AVG(r.rank),0) 
          AS avrank
          FROM stories s                  
          LEFT JOIN ratings 
          AS r ON r.storyidr = s.id
          WHERE title 
          LIKE '%$find%'
          LIMIT 50;
Was it helpful?

Solution

You are getting one result only because you are calculating the average .. In order to get multiple results while using a function like AVG() or COUNT() etc .. You need to use GROUP BY

You might try something like this:

          SELECT s.*, 
          ROUND(AVG(r.rank),0) 
          AS avrank
          FROM stories s                  
          LEFT JOIN ratings 
          AS r ON r.storyidr = s.id
          GROUP BY title 
          HAVING title 
          LIKE '%$find%'
          LIMIT 50;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top