26

我有一个“文件夹”表。我想返回 userId 为 16 的所有记录。

SELECT * FROM `folders` WHERE userId = 16;

我有一个“文件”表。对于上面返回的每个“文件夹”,我想返回该“文件夹”内的“文件”计数。

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

我如何结合这些?我迷路了。谢谢!

4

4 回答 4

52
SELECT  fol.*
 ,      (       SELECT  COUNT(*)
                FROM    files           fil
                WHERE   fil.Folder      = fol.Folder
        )       AS      "Files"
FROM    folders         fol
WHERE   fol.userId      = 16

它被称为相关子查询。

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

于 2009-03-01T02:37:54.267 回答
15

您可能需要使用 GROUP BY 并按 ID 等对其进行分组:

SELECT 
    folders.*,
    COUNT(files.*) as filetotal 
FROM folders 
    LEFT JOIN files ON folders.ID=files.folderID 
WHERE userId = 16 
GROUP BY folders.ID
于 2009-02-28T17:36:15.740 回答
4

执行按文件夹分组的子查询以获取每个文件夹的计数,然后将其加入到第一个查询中,如下所示:

    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
于 2009-02-28T17:38:52.597 回答
2
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



如果您不想使用 group by 语句。


我在产品列表中遇到了类似的问题,我想计算另一个表 [1-5] 中产品的星级以及投票支持该特定产品的用户数量。

于 2011-05-27T08:55:57.047 回答