使用最快的查询从

时间:2017-03-23 00:24:40

标签: php mysql yii2

我有一张这样的桌子。

enter image description here

我想得到"成本"根据日期和时间以最快的查询。

例如:

输入:

id_room = 1;
date = 2017/03/24
time from: 05:30:00
time end: 07:30:00

专栏"费用"是指每小时的成本。

如何从timeFrom到timeEnd获得成本金额?

1 个答案:

答案 0 :(得分:1)

简而言之:

SELECT SUM((time_to_sec(timediff(LEAST('07:30:00', timeTo), GREATEST('05:30:00', timeFrom))) / 3600) * cost)
FROM `roomcost` r
WHERE WEEKDAY('2017-03-23') BETWEEN dayFrom AND dayTo 
AND (timeFrom <= '05:30:00' OR timeTo >= '07:30:00')
AND id_room = 1

我的测试数据:

INSERT INTO `roomcost` (`id`, `id_room`, `dayFrom`, `dayTo`, `timeFrom`, `timeTo`, `cost`) VALUES
(1, 1, 1, 6, '05:00:00', '06:00:00', '50.00'),
(2, 1, 1, 6, '06:00:00', '17:00:00', '100.00'),
(3, 1, 0, 0, '05:00:00', '10:00:00', '200.00');

说明:

  1. 从您的roomcost表中选择所有有效行。 WEEKDAY为您提供给定日期的工作日日期
  2. 使用GREATESTLEAST,您可以获得相交的时间范围。
  3. 使用timedifftime_to_sec
  4. 计算小时数差异
  5. 总结
  6. SELECT r.*, GREATEST('05:30:00', timeFrom) AS startTime, LEAST('07:30:00', timeTo) AS endTime , time_to_sec(timediff(LEAST('07:30:00', timeTo), GREATEST('05:30:00', timeFrom))) / 3600 , (time_to_sec(timediff(LEAST('07:30:00', timeTo), GREATEST('05:30:00', timeFrom))) / 3600) * cost FROM {roomcost {1}}