MySQL statement combining a join and a count?

前端 未结 4 1632
梦如初夏
梦如初夏 2020-12-08 01:40

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

相关标签:
4条回答
  • 2020-12-08 01:42

    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
    
    0 讨论(0)
  • 2020-12-08 01:52
    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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-08 02:07

    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
    
    0 讨论(0)
提交回复
热议问题