如何根据另一个表

时间:2015-10-21 10:42:06

标签: mysql

如何根据另一个表中的两个日期字段获取一个表中的记录数

例如:
表1:离开

| leav_id     | from      | to             |


| 1           | 2015-10-20 | 2015-10-27    |

| 2           | 2015-11-10 | 2015-10-12    |

表2:假期

| holi_id     | On         | Name       |


| 1           | 2015-12-25 | Christmas  |

我想获得number days between from and to in table leaves excluding the count of holidays from table holiday in that range

3 个答案:

答案 0 :(得分:1)

以下是您可以做的事情,我已经为计算创建了更多假期

mysql> select * from leaves ;
+---------+------------+------------+
| leav_id | from       | to         |
+---------+------------+------------+
|       1 | 2015-10-20 | 2015-10-27 |
|       2 | 2015-12-20 | 2015-12-30 |
+---------+------------+------------+
2 rows in set (0.00 sec)

mysql> select * from holidays ;
+---------+------------+----------+
| holi_id | on         | name     |
+---------+------------+----------+
|       1 | 2015-12-25 | X-Mass   |
|       2 | 2015-12-26 | Saturday |
|       3 | 2015-12-26 | Sunday   |
|       4 | 2015-10-24 | Saturday |
|       5 | 2015-10-25 | Sunday   |
+---------+------------+----------+

因此,以下查询将为您提供不包括假期的总叶数

select 
t1.leav_id,
( 
  datediff(t1.`to`,t1.`from`) 
  - 
  sum(
    case when t2.`on` >= t1.`from` and t2.`on` <= t1.`to` 
    then 1 else 0  end
  ) 
) as total_leave
from  leaves t1 
left join holidays t2 on t2.`on` >= t1.`from` 
and t2.`on` <= t1.`to` 
group by t1.leav_id 

结果将为

+---------+-------------+
| leav_id | total_leave |
+---------+-------------+
|       1 |           5 |
|       2 |           7 |
+---------+-------------+

另请注意,datediff函数可能无法为您提供正确的结果,例如

mysql> select datediff('2015-12-30','2015-12-20') as d ;
+------+
| d    |
+------+
|   10 |
+------+

这是10天,但是当假期计算为11时,即从2015-12-202015-12-30

因此需要重新考虑上述查询以将+1添加为

select 
t1.leav_id,
( 
  datediff(t1.`to`,t1.`from`) 
  - 
  sum(
    case when t2.`on` >= t1.`from` and t2.`on` <= t1.`to` 
    then 1 else 0 end
   ) 
 )+1 as total_leave
from  leaves t1 
left join holidays t2 on t2.`on` >= t1.`from` 
and t2.`on` <= t1.`to` 
group by t1.leav_id 

并将作为

+---------+-------------+
| leav_id | total_leave |
+---------+-------------+
|       1 |           6 |
|       2 |           8 |
+---------+-------------+

答案 1 :(得分:0)

首先使用datediff: -

select datediff(to, from) as day from leaves

答案 2 :(得分:0)

我已经编辑了我的答案,请你试试这个。

SELECT l.*, 
datediff(l.`to`, l.`from`) as leavedays,
IF((SELECT h.holiday FROM holidays AS h WHERE h.holiday between l.`from` AND l.`to`)<>'',1,0) AS holyday,
(datediff(l.`to`, l.`from`)-(SELECT IF(count(h.holiday)='',0,count(h.holiday)) FROM holidays AS h WHERE h.holiday between l.`from` AND l.`to`) AS totalday
FROM
leaves AS l