Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need some assistance cleaning up a query. 1

Status
Not open for further replies.

ochaos

Programmer
Sep 9, 2008
18
US
Hello,

Currently, I have a couple of queries that are taking a couple seconds to process and load the page and I was wondering if you could point me in the right direction to clean this up.

I have two tables that are being accessed over 2 queries right now.

This query grabs all the beer names for one brewery
Code:
SELECT beer.beer_id,beer.beer_name
FROM beer
WHERE beer.brewery_id='some_id'
ORDER BY beer.beer

Then I take those results and loop through them to also display some stats about the beer. (number reviews, average score etc.)

Code:
foreach($result do this){
   SELECT AVG(total) AS score, COUNT(beer_id) AS review_count   ,MAX(total) AS high_score ,MIN(tot) AS low_score 
   FROM `ratings` 
   WHERE beer_id='".$row->beer_id."'
}

I was trying to use a JOIN like so, but as soon as I do, it limits the results to one row.

Code:
SELECT beer.beer_id,beer.beer_name,AVG(total)
FROM beer
JOIN ratings ON ratings.beer_id=beer.beer_id
WHERE beer.brewery_id='some_id'
ORDER BY beer.beer

Is it possible to do what I am trying to do with one query? I assume it will cut my page load time down significantly if I can consolidate it.

Thank you
 
I just noticed that when typing this to clean it up, ORDER BY in both queries should be ORDER BY beer.beer_name
 
Hi

What is your goal ? If you want to get a list of all bears together with each bear's rating statistics, then you should use [tt]group by[/tt] on beer.brewery_id and beer.beer_name and no [tt]where[/tt] condition.


Feherke.
 
Code:
SELECT beer.beer_id
     , beer.beer_name
     , AVG(ratings.total) AS score
     , COUNT(*) AS review_count   
     , MAX(ratings.total) AS high_score 
     , MIN(ratings.total) AS low_score    
  FROM beer
INNER
  JOIN ratings    
    ON ratings.beer_id = beer.beer_id
 WHERE beer.brewery_id = [i]some_id[/i]
GROUP
    BY beer.beer_id
ORDER 
    BY beer.beer_name

r937.com | rudy.ca
Buy my new book Simply SQL from Amazon
 
Thanks for the replies. r937's query gets me most of the way there, it's not displaying the beer names for the beers without reviews on them, but I will be able to tweak this query to include those when I have a couple minutes.

Thank you, I didn't think to group the results, my understanding of it was a little off it appears.

Thanks again!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top