【问题标题】:Query with IF statement用 IF 语句查询
【发布时间】:2012-02-03 08:10:56
【问题描述】:

我有一个关于 MYSQL 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 with condition to above request:

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

谢谢!

【问题讨论】:

    标签: mysql select if-statement


    【解决方案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)
    

    【讨论】:

      【解决方案2】:

      只需将其添加到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
       ...
      

      也会有同样的效果。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-06-24
        • 2019-10-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多