我的MySQL查询有点麻烦

时间:2015-12-17 17:46:02

标签: mysql

My MySQL Query

好的,所以我试图添加另一个列(leave_remaining),如果leave_status是“确定”,则会显示该列。然后,leave_remaining将显示员工离开的休假天数。我一直在犯这个错误。这里的语法是什么?谢谢

这有效:

select id,leave_started,leave_ended,no_of_leave_allowed, 
leave_ended-leave_started AS no_of_leaves_taken, 
if (leave_ended-leave_started >no_of_leave_allowed, 
 'leave exceeded','ok')as leave_status
from leave_taken;

这不是:

if (leave_status,'ok', 
(no_leave_allowed-no_leaves_taken))as leave_remaining
 from leave_taken;
select * from leave_taken;

2 个答案:

答案 0 :(得分:0)

如果我正确理解你,我想你想要这个:

SELECT
    id, leave_started, leave_ended, no_of_leave_allowed, 
    (leave_ended - leave_started) AS no_of_leaves_taken, 
    IF(
        (leave_ended - leave_started) > no_of_leave_allowed,
        'leave exceeded',
        'ok'
    ) AS leave_status,
    IF (
        (leave_ended - leave_started) > no_of_leave_allowed,
        (no_of_leave_allowed - (leave_ended - leave_started)),
        0
    ) AS leave_remaining
FROM leave_taken;

虽然不确定您如何定义leave_startedleave_ended,但您可以将其减去......

http://sqlfiddle.com/#!9/16cdb3/6

答案 1 :(得分:0)

SELECT必须在IF之前,尽管你没有做任何事情。

正确的陈述是

SELECT something as alias, something_else as alias_else, if(,,) as alias_if
FROM table
WHERE where = clause

当您必须使用某个语句(例如IF或CASE)时,会产生一个字段,它必须在select中。