如何计算A表中的所有记录,其中B表具有2条以上的记录

时间:2018-07-25 09:00:59

标签: mysql

嗨,我正在尝试计算所有获得2个以上订单的用户。

我到目前为止所做的是

SELECT Count(*), 
   (SELECT Count(*) AS cnt 
    FROM   order ord 
    WHERE  usr.id = ord.user_id 
    HAVING cnt > 1) 
FROM   USER usr; 

但是我仍然有总用户

5 个答案:

答案 0 :(得分:3)

您可以这样写:

Select count(*)
from (
Select UserId, Count(UserId) from Order group by UserId having Count(UserId)>2
) Temp

答案 1 :(得分:1)

尝试此操作以获取用户明智的订单计数

SELECT usr.id, Count(ord.id)
FROM USER usr
INNER JOIN order ord ON usr.id = ord.user_id 
GROUP BY usr.id
Having Count(ord.id)>2

如果您要计算超过2个订单的用户数

SELECT count(distinct usr.id)
FROM USER usr
INNER JOIN order ord ON usr.id = ord.user_id 
GROUP BY usr.id
Having Count(ord.id)>2

答案 2 :(得分:1)

我只是尝试修复您的查询,因为我发现您在投影上确实犯了错,这就是为什么我使用子查询

SELECT * from 
   (    
    SELECT usr.id, Count(*) AS cnt 
    FROM   order ord 
    inner join USER usr
    on usr.id = ord.user_id
    group by usr.id   
    HAVING cnt >2
) as T

答案 3 :(得分:1)

尝试一下:

SELECT Count(*) FROM   USER usr
WHERE EXISTS(SELECT 1 FROM order
             WHERE user_id = usr.id
             GROUP BY user_id
             HAVING COUNT(*) >= 2)

答案 4 :(得分:1)

让您将查询分为两部分:

  1. 所有完成2个以上订单的用户:

    SELECT user_id, COUNT(*) AS count FROM orders  
    GROUP BY user_id  
    HAVING COUNT(*) > 2;
    
  2. 从以上结果中计算所有用户:

    SELECT COUNT(*) AS total FROM (
        SELECT user_id FROM orders  
        GROUP BY user_id  
        HAVING COUNT(*) > 2
    ) required_users;