How to make a SELECT query in Hibernate includes Subquery COUNT(*)

后端 未结 3 1276
说谎
说谎 2021-01-05 18:03

Let\'s say we have a Category - Items one-to-many relation. I would like to do this

SELECT c.*, 
   (SELECT COUNT(*) FROM items i W         


        
3条回答
  •  轮回少年
    2021-01-05 18:38

    Depending on your circumstances and ability to create a view. I would just create a view out of your query:

    CREATE VIEW CategoryItemsView AS 
        SELECT c.*,  
       (SELECT COUNT(*) FROM items i WHERE i.catId=c.id) 
        AS itemCount 
    FROM category c 
    

    afterwards you can query how ever you like...

    SELECT * FROM CategoryItemsView WHERE ItemCount = 5
    

    Additionally, you could use a GROUP BY to achieve a similar result but that depends on your columns and the schema of your tables.

    So, something like this:

    SELECT c.COLUMN1, c.COLUMN2, COUNT(*) AS ItemCount
    FROM category c inner join items i on i.catID = c.Id
    GROUP BY c.COLUMN1, c.COLUMN2
    HAVING COUNT(*) = 2
    

提交回复
热议问题