문제

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;
도움이 되었습니까?

해결책

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;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top