用IF语句查询

时间:2012-01-05 13:46:58

标签: mysql select if-statement

我对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

谢谢!

2 个答案:

答案 0 :(得分: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
 ...

它会产生同样的效果。

答案 1 :(得分: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)