PHP/MySQL join statement
html, mysql, php, sql
Solution
Your SQL query is invalid. You need to either omit `s.store_name` from the query or include it in the GROUP BY
SELECT
s.store_id,
s.store_name,
AVG(r.rating) AS
FROM stores as s
JOIN reviews as r ON s.store_id = r.store_id
GROUP BY s.store_id, s.store_name
Problem
I am trying create an average rating for a store listing using MySQL's `AVG` and then displaying the average next to each store on a directory list page. Every time someone leaves a review for a store, they give a rating of 1-5, which is inserted into `TABLE reviews` in column `rating`. The store data is coming from `TABLE reviews` and the table relationship is coming from a column in both tables named `store_id`. I trying to use a join statement to get the average to display next to each store. This is the current code in the loop for the rating with join statement: ``` <?php echo "<table>\n"; echo "<tr><th>Store ID</th><th>Rating</th></tr>\n"; $result1 = mysql_query("SELECT s.store_id AVG(r.rating) AS avg_rating FROM stores as s JOIN reviews as r ON s.store_id = r.store_name GROUP BY s.store_id"); while ($row1 = mysql_fetch_assoc($result1)) { echo "<tr><td>$row1[store_id]</td><td>$row1[avg_rating]</td></tr>\n"; } echo "</table>\n";?> echo "</table>\n";?> ``` This is the SQL error I am getting You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(r.rating) AS avg_rating FROM stores' This is the PHP error I am getting: Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in /home/shopping/public_html/retailers.php on line 227 Line 227 is this line from the code above: ``` while ($row1 = mysql_fetch_assoc($result1)) { ``` These are my tables' two structures: ``` CREATE TABLE `stores` ( `store_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `store_name` varchar(255) NOT NULL DEFAULT '', CREATE TABLE `reviews` ( `rating_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `store_id` int(11) NOT NULL DEFAULT '0', `rating` tinyint(1) NOT NULL DEFAULT '0', ```