tags:

views:

119

answers:

3

hello i have 2 tables:

tblItems 
ID           |     orderID             | productID
1                   1                     2
2                   1                     2
3                   2                     1
4                   3                     2

tblProducts
productID    |     productName
1                   ABC
2                   DEF

im attempting to find the most popular Product based on whats in "tblItems", and display the product Name and the number of times it appears in the tblItems table.

i can get mysql to count up the total like:

$sql="SELECT COUNT(productID) AS CountProductID FROM tblItems";

but i can't figure out how to join the products table on..if i try LEFT JOIN the query goes horribly wrong

hopefully thats not too confusing..thankss

A: 

I think you may be looking for something like:

SELECT tblProducts.productName, COUNT(tblItems.ID)
FROM tblProducts
LEFT JOIN tblItems USING(productID)
GROUP BY tblProducts.productID
Alex Martelli
oh wow that works almost perfectly, thank you! it does return all products however, even if they don't appear in "tblItems". But it does count everything as i wanted. thanks.
calum
@Alex Martelli - I'm a bit surprised this query runs. You have productName in the SELECT statement but not in the GROUP BY.
Thomas
@Thomas, mysql is traditionally relaxed in this regards -- it just gives you any one value of the field in the group's records (so it's fine when all such values are identical, like here). I wouldn't recommend it in _standard_ SQL of course;-).
Alex Martelli
@calum, if you *don't* want products that don't appear in the table items, just drop the word `LEFT` from the query -- you specifically mentioned `LEFT JOIN` so of course I thought you **did** want them!
Alex Martelli
A: 

Are you simply trying to find the count of orders by product like so:

Select P.ProductName, Count(*)
From tblItems As I
    Join tblProducts As P
        On P.ProductId = I.ProductId
Group By P.ProductName
Thomas
this was spot on, great thanks.
calum
A: 
SELECT count(i.productID) AS cnt, p.productName FROM tblItems AS i
LEFT JOIN tblProducts AS p ON p.productID = i.productID
GROUP BY i.productID
ORDER BY cnt desc
Frank Shearar