开发者

MYSQL COUNT and only show results above X

开发者 https://www.devze.com 2023-01-01 04:42 出处:网络
Is it possible to count all reservations for users and only get results where users have had more than X reservations. Here is my code to just count all user\'s reservations

Is it possible to count all reservations for users and only get results where users have had more than X reservations. Here is my code to just count all user's reservations

SELECT 
    u.firstname, u.la开发者_开发百科stname u.email, COUNT(r.reservation_id) as orders
FROM 
    users AS u LEFT OUTER JOIN
    reservation AS r USING (user_id)
GROUP BY
    u.id

Can I add to this query to say WHERE orders >= 5 ??

Hope you can advise

Lee


You want to use 'HAVING' not 'WHERE' when you're acting on aggregation:

SELECT 
    u.firstname, u.lastname u.email, COUNT(r.reservation_id) as orders
FROM 
    users AS u LEFT OUTER JOIN
    reservation AS r USING (user_id)
GROUP BY
    u.id
HAVING orders >= 5;

(I think mysql allows you to column aliases in the HAVING clause ... postgres doesn't, so you'd have to use HAVING COUNT(r.reservation_id) >= 5)


take a look at the HAVING option that should let you do what you want.


not sure if mysql has this: but in Oracle,

HAVING COUNT(*) > 5 

is available

0

精彩评论

暂无评论...
验证码 换一张
取 消