2012-01-05 15 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を必要とするので、声明はまた、CASEまたはIFずに書くことができます。

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

、それは同じ効果を持つことになります。

関連する問題