tags:

views:

1969

answers:

4

I've got a table of 'folders'. I want to return all the records with the userId of 16.

SELECT * FROM `folders` WHERE userId = 16;

I've got a table of 'files'. For each 'folder' returned above, I want to return a count of 'files' within that 'folder'.

SELECT COUNT(*) as "Files" FROM files WHERE Folder = n;

How do I combine these? I'm lost. Thanks!

+3  A: 

you would probably need to use GROUP BY and group it by ID or such:

SELECT 
    folders.*,
    COUNT(files.*) as filetotal 
FROM folders 
    LEFT JOIN files ON folders.ID=files.folderID 
WHERE userId = 16 
GROUP BY folders.ID
dusoft
This is wrong. The columns referenced in folders.* have to be in the GROUP BY clause. All columns in a SELECT statement with a GROUP BY have to either be in a GROUP BY or an aggregate function.
entaroadun
yeah, that's why i am groupping by folders.ID (one column is enough to group on).
dusoft
To get this to work you will need to GROUP BY all of the required columns from "folders" that are mentioned in the SELECT clause - I tested the theory of "one column is enough to group on" and it's not true in SQL Server 2005 at least.
Rich Andrews
It's never a good idea to use SELECT * anyway but to specify all of the columns to be returned explicitly.
Rich Andrews
he had there * in his original query, i don't know what his table looks like, so stop trolling and use your wits for something creative.
dusoft
Sweet syntactic sugar: <http://dev.mysql.com/doc/refman/5.0/en/group-by-hidden-columns.html>. That'll teach me to talk about a product I don't use every day.
entaroadun
A: 

is the userid in the files table? can you groupby the userid and then apply the count to each user?

Pete
A: 

Do a sub query that groups by the Folders to get the count per folder, then join it to the first query like this:

    select
       f.*
       fc.Files
    from
       Folders f
--
       -- Join the sub query with the counts by folder     
       JOIN (select
               Folder,
               count(*) Files
             from
                files
             group by
                Folder ) as fc
          on ( fc.Folder = f.Folder )
    where
       f.userid = 16

Ron

Ron Savage
+5  A: 
SELECT  fol.*
 ,      (       SELECT  COUNT(*)
                FROM    files           fil
                WHERE   fil.Folder      = fol.Folder
        )       AS      "Files"
FROM    folders         fol
WHERE   fol.userId      = 16

It's called a correlated subquery.

http://dev.mysql.com/doc/refman/5.1/en/correlated-subqueries.html

entaroadun