2012-01-05 163 views
0

我有一個關於MYSQL If語句的問題。 我的要求:使用IF語句查詢

SELECT c.status, c.thumb, j.id, j.name, j.username, s.session_id, a.time, a.isactive, a.country, a.countrycode, a.city 
FROM j16_users AS j 
JOIN j16_community_users AS c ON c.userid = j.id 
LEFT JOIN j16_session AS s ON s.userid = j.id 
LEFT JOIN j16_session AS s ON s.userid = j.id 
LEFT JOIN j16_x5_fastchat_users AS a ON a.userid = j.id 
WHERE j.id IN (62,66,2692) 

我如何添加一個新柱:有狀態isonline上述要求:

IF(a.time > DATE_SUB(NOW(), INTERVAL 1 MINUTE), "1", "0") AS isonline 

謝謝!

回答

1
SELECT c.status, c.thumb, 
     j.id, j.name, 
     j.username, s.session_id, 
     a.time, a.isactive, 
     a.country, a.countrycode, a.city, 
     IF(a.time > DATE_SUB(NOW(), INTERVAL 1 MINUTE), 1, 0) AS isOnline 
FROM j16_users AS j 
    JOIN j16_community_users AS c ON c.userid = j.id 
    LEFT JOIN j16_session AS s ON s.userid = j.id 
    LEFT JOIN j16_session AS s ON s.userid = j.id 
    LEFT JOIN j16_x5_fastchat_users AS a ON a.userid = j.id 
WHERE j.id IN (62,66,2692) 
1

只需將其添加到SELECT列表中。建議使用CASE statement,因爲它更便於攜帶。

SELECT 
    c.status, 
    c.thumb, 
    j.id, 
    j.name, 
    j.username, 
    s.session_id, 
    a.time, 
    a.isactive, 
    a.country, 
    a.countrycode, 
    a.city, 
    CASE WHEN a.time > DATE_SUB(NOW(), INTERVAL 1 MINUTE) THEN 1 ELSE 0 END AS isonline 
FROM 
    j16_users AS j 
    JOIN j16_community_users AS c ON c.userid = j.id 
    LEFT JOIN j16_session AS s ON s.userid = j.id 
    LEFT JOIN j16_session AS s ON s.userid = j.id 
    LEFT JOIN j16_x5_fastchat_users AS a ON a.userid = j.id 
WHERE 
    j.id IN (62,66,2692) 

因爲你只需要一個布爾值1或0,語句也可以不CASEIF書面:

... 
a.countrycode, 
a.city, 
(a.time > DATE_SUB(NOW(), INTERVAL 1 MINUTE)) AS isonline 
... 

,這將有同樣的效果。