SQL JOIN COUNT然后在where子句中使用该计数值

时间:2017-03-31 23:12:48

标签: mysql sql count

我试图选择用户评级(user.rating)是否大于6,或者用户是否有超过100个事务(事务表计数)。基本上计算用户拥有的交易数量(交易次数> = 100或用户评级> = 6)。

SELECT *
FROM   `user`
JOIN   (SELECT COUNT(*) 
        FROM   transaction 
        WHERE  transaction.user_id=user.id 
        AND type='L' 
        AND status='S') AS tcount 
WHERE  (user.rating >= '6' OR tcount >= '100')

3 个答案:

答案 0 :(得分:2)

在COUNT(*)

上使用别名
SELECT *
FROM   `user`
JOIN   (SELECT user_id, COUNT(*) cnt
        FROM   transaction 
        WHERE type='L' 
        AND status='S'
        GROUP BY user_id) AS tcount 
ON      user.id = tcount.user_id
WHERE  (user.rating >= '6' OR tcount.cnt >= '100')

答案 1 :(得分:2)

另一个可能的答案。我已经创建了简化的模式来测试它,请尝试并告诉我结果。

SELECT * 
FROM user
WHERE user.rating >= 6 OR (SELECT COUNT(*) FROM transaction WHERE user_id = user.id and type = 'L' and status = 'S') >= 100;

答案 2 :(得分:0)

您可以在没有子查询的情况下编写,如此

SELECT  u.id
FROM `user` u
JOIN `transaction` t
ON t.user_id=u.id 
WHERE t.type = 'L' AND t.status = 'S'
GROUP BY u.id
HAVING sum(case when u.rating >= 6 then 1 end) > 0 OR count(*) >= 100