协助根据条件编写mysql查询

时间:2012-11-04 21:09:45

标签: mysql

我试图根据if语句编写MySQL语句。

这就是我想要做的事情:我需要查询根据项目是否将在两周内到期或者是否已经过期而收集行。

这是我到目前为止所做的:

select
  t_id,
  firstName, 
  lastName, 
  checkTime,
  due
from (checkOut join People)
where checkOut.p_id = People.p_id
order by due IF(DATE(NOW()-checkOut.due) <= 2 WEEK);

MySQL声称在IF语句附近存在语法错误(我并不感到惊讶,因为我不熟悉在MySQL中编写条件语句)。

另一个问题是关于MySQL是否会产生一个否定的日期(即表示项目是否已到期)。提前谢谢。

2 个答案:

答案 0 :(得分:1)

IF无法使用。可移植的替代方法是在CASE中放置ORDER BY以分配条件匹配的0,并10之后排序select t_id, firstName, lastName, checkTime, due from checkOut join People ON checkOut.p_id = People.p_id order by /* Use DATE_SUB() */ /* This will sort those not yet past due ahead of those already past due. If this is the opposite of what you want, switch the 0 and 1 */ CASE WHEN DATE_SUB(CURDATE(), INTERVAL 2 WEEK) <= checkOut.due THEN 0 ELSE 1 END; 吨。

WHERE

请注意,我已将隐式联接转换为显式联接,方法是将ON子句更改为{{1}}子句。

答案 1 :(得分:1)

我认为你要找的是这个,

SELECT t_id, 
       firstname, 
       lastname, 
       checktime, 
       due 
FROM   checkout 
       JOIN people 
         ON checkout.p_id = people.p_id 
ORDER  BY CASE 
            WHEN ( Now() - INTERVAL 2 week ) <= checkout.due THEN 0 
            ELSE 1 
          END, 
          due