简体   繁体   中英

Query for counting items under parent category from a different table

I have stockcards and stockcategories table.

I want to display categories and show how many stockcards is openned under this category.

SELECT a.stockCatID, a.stockCatName, f.nProductsInside 
FROM stockcategories a 
LEFT JOIN 
        (
            SELECT COUNT(b.stockID) AS nProductsInside 
            FROM stockcards b 
        ) 
        f ON a.stockCatID = f.stockCatID 

Well it returns #1054 - Unknown column 'f.stockCatID' in 'on clause' Obviously I am making a mistake..

try with something like:

SELECT a.stockCatID, a.stockCatName, COUNT(b.stockID) AS nProductsInside
FROM stockcategories a 
LEFT JOIN stockcards b ON a.stockCatID = b.stockCatID
GROUP BY a.id

where a.id is the primary key in the stockcategories table

SELECT a.stockCatID, a.stockCatName, COUNT(b.stockID) as nProductsInside 
FROM stockcategories a 
LEFT JOIN stockcards b ON a.stockCatID = b.stockCatID 
group by a.stockCatID

You could probably do this too (unverified) ni order to stick with your query

SELECT a.stockCatID, a.stockCatName, f.nProductsInside 
FROM stockcategories a 
LEFT JOIN 
(
    SELECT COUNT(b.stockID) AS nProductsInside, stockCatID
    FROM stockcards b 
) 
f ON a.stockCatID = f.stockCatID 

f是SELECT COUNT(b.stockID)的结果的别名...因此f没有列

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM