从mysql数据库计算叶子

时间:2016-07-07 15:56:20

标签: php mysql

我有一张这样的休假表:

**employeeId    action      type       effective_date**
   1            leave       paid        2016-01-15
   2            leave       unpaid      2016-01-16
   1            return      return       2016-01-17
   2            return      return       2016-01-17

我尝试了这个查询:

$query = (select * from table where employeeId = "$empID" && type = "$type");
在此之后我被困住了;实际上我想要:

where Empid = 1 && action = leave && type = paid orderby effective_date

$i=0;
$j=$i+1;
$leave =0;
while($row = mysqli_fetch_array($query)){

    $leave = $row['effective_date'][$i] - $row['effective_date'][$j];
    $i+1;
    $j+1;
    $leaves = $leaves+$leave;
} 
你可以帮我纠正一下吗?或者有更好的计算假期的方法吗?

1 个答案:

答案 0 :(得分:0)

您必须在ORDERBY

之间留出空格
SELECT * FROM `employee`
    WHERE `employeeId`='1'
    AND   `action` = 'leave'
    AND   `type` = 'paid'
ORDER BY  `effective_date` ASC

<强>输出

+------------+--------+------+---------------------------+
| employeeId | action | type |            effective_date |
+------------+--------+------+---------------------------+
|          1 |  leave | paid | January, 15 2016 00:00:00 |
+------------+--------+------+---------------------------+

小提琴:http://sqlfiddle.com/#!9/5bac3/3

这会给你一些叶子:

SELECT `employeeId`, COUNT(*) AS `NumLeaves` FROM `employee`
    WHERE `employeeId`='1'
    AND   `action` = 'leave'
    AND   `type` = 'paid'
GROUP BY `employeeId`
ORDER BY  `effective_date` ASC

<强>输出

+------------+-----------+
| employeeId | NumLeaves |
+------------+-----------+
|          1 |         1 |
+------------+-----------+

小提琴:http://sqlfiddle.com/#!9/5bac3/6