2012-01-05 132 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 
... 

,这将有同样的效果。