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
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
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
select
f.`folder`,
f.`userId`,
r.`count`
from
`folders` f
left join
(
select
`Folder`,
count(`id`) `count`
from `files`
group by `Folder`
) r
on r.`Folder`=f.`folder`
where
`userId`=16
if you do not want to use the group by statement.
i had a simmilar problem in a product list where i wanted to count the star rating of a product in another table [1-5] and the amount of users that voted for that specific product.
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