2014-09-20 70 views
0

我有一個連接到點的數據的MySQL表。像這樣:Mysql:選擇指定點之間的所有數據

tbl_user

tbl_earned_points

tbl_used_points

我有一個MySQL查詢選擇可用點的數據。這是查詢:

SELECT 
user.user_email_id AS userEmailId, 
IFNULL(SUM(earn_points.earned_points),0) AS lifeTimePoints, 
IFNULL((SUM(earn_points.earned_points) - (SELECT IFNULL(SUM(used_points.points_used),0) FROM tbl_used_points AS used_points WHERE used_points.user_id=earn_points.user_id)),0) AS availablePoints 
FROM tbl_earned_points AS earn_points 
RIGHT JOIN tbl_user AS user ON earn_points.user_id=user.user_id WHERE user.user_email_id <> '' AND user.user_email_id <> '0' 
GROUP BY user.user_email_id 
ORDER BY availablePoints ASC 

從上面的查詢我收到的所有電子郵件&結果像

userEmailId    lifeTimePoints  availablePoints 
[email protected]  1745    1500 
[email protected] 100    75 
[email protected]   85     85 
[email protected]   94     90 
[email protected]  547    450 

我的問題是,我只需要得到各行availablePoints 80到99

所以會導致我的查詢像

userEmailId  lifeTimePoints  availablePoints 
[email protected]  85    85 
[email protected]  94    90 

回答

0

只需添加到您的WHERE子句:

AND availablePoints BETWEEN 80 AND 99 
+0

#1054 - 在 'where子句' – user2046091 2014-09-20 06:50:48

0

您可以使用BETWEEN子句availablePoints。無論你想要什麼,請設置你的availablePoints

+0

如果我添加未知列 'availablePoints' 「AND availablePoints 80-99」 在where子句然後它給 #1054 - 在 'where子句' – user2046091 2014-09-20 06:51:51

0

基本上你只需要添加WHERE條件。但是,您也可以重寫查詢以刪除相關子查詢,只需使用OUTER JOINs

SELECT u.user_email, 
    COALESCE(e.points,0) lifeTimePoints, 
    COALESCE(a.points,0) availablePoints 
FROM tbl_user AS u 
    LEFT JOIN (
     SELECT SUM(earned_points) points, user_id 
     FROM tbl_earned_points 
     GROUP BY user_id 
    ) e ON u.user_id = e.user_id 
    LEFT JOIN (
     SELECT SUM(points_used) points, user_id 
     FROM tbl_used_points 
     GROUP BY user_id 
    ) a ON u.user_id = a.user_id 
WHERE a.points between 80 and 99 

如果您更願意使用現有的查詢,你要麼需要將其包裝在一個子查詢和使用列別名(availablepoints),或者您需要在WHERE條件中使用整個IFNULL語句。 您不能直接引用列別名。

+0

未知列 'availablePoints'使用外連接\ n SELECT USER_ID FROM (SELECT USER_ID,SUM(earned_points)從tbl_earned_points點積分,其中GROUP BY user_ID的)AS總結WHERE點80至99 從上面的查詢我得到的結果是沒有得到正確的1761行 從您的查詢我得到只有25行 – user2046091 2014-09-20 06:54:44

+0

@ user2046091 - 它不應該返回t相同的結果,它應該只返回80到99之間的可用點。但是,如果你在沒有WHERE標準的情況下運行它,那麼它應該返回相同數量的結果。 – sgeddes 2014-09-20 13:44:22