View Single Post
Old 10-10-2012, 07:23 AM   PM User | #8
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,556
Thanks: 62
Thanked 4,055 Times in 4,024 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
Ahhh...yes, I see that.

The problem occurs because, again, your DB isn't normalized. If it were, you would have a separate CATEGORIES table, where each category had a categoryid (INT PRIMARY KEY) and cateogoryname. And then, in your OFFERS table, you would use the categoryid instead of the name. You really should read up on NORMALIZATION. Your lack of it is causing you all sorts of efficiency griefs.

So lacking that separate CATEGORIES table...

We could fix it by just changing the first SELECT to SELECT DISTINCT, but that won't be efficient.

So try this...
Code:
$sql = "SELECT OS.category, IFNULL(SS.thecount, 0) AS howmany "
    . " FROM ( SELECT DISTINCT category FROM offers ) AS OS " 
    . " LEFT JOIN ( "
    .     " SELECT O.category, COUNT(*) AS thecount " 
    .     " FROM offers AS O LEFT JOIN completed_offers AS C"
    .     " ON ( O.offerid = C.offerid AND C.username='$usr' ) "
    .     " WHERE O.countries LIKE '%$country%' "
    .     " AND C.offerid IS NULL "
    .     " GROUP BY O.category ) AS SS "
    . " ON OS.category = SS.category " 
    . " ORDER BY OS.category";
If it's not obvious, SELECT DISTINCT category FROM offers is, essentially, building the missing CATEGORIES table. But it's a much more expensive operation than if you actually had such a table.
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is offline   Reply With Quote
Users who have thanked Old Pedant for this post:
markman641 (10-10-2012)