2017-03-31 98 views
0

我試圖選擇用戶評級(user.rating)是否大於6或用戶是否有超過100個事務(事務表計數)。基本上統計用戶的交易次數(交易次數> = 100或用戶評級> = 6)。SQL JOIN COUNT然後在where子句中使用該計數值

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') 

回答

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; 
+0

更改爲這個,因爲它使用較少的代碼。 –

+0

@MarcAlexander thx:) –

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') 
+0

它在'where子句'中給我未知列'user.id' –

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