简体   繁体   English

根据基于多行的日期/时间范围选择记录

[英]Select record based on date/time range based on multiple rows

I have following table structure 我有以下表格结构

id          date             time            discount
------------------------------------------------------
1         2015-08-10       09:30:00           50%
2         2016-04-15       14:00:00           30%
3         2018-01-25       18:15:00           75%
4         2018-11-19       11:45:00           45%

I want to query this table to find the discount amount on specific date; 我想查询该表以查找特定日期的折扣金额;

expected result; 预期结果;

if I query for a date between 2015-08-10 09:30:00 - 2016-04-15 13:59:59 it should result 50% 如果我查询的日期介于2015-08-10 09:30:00 : 2016-04-15 13:59:59 ,则结果应为50%

for a date between 2016-04-15 14:00:00 - 2018-01-25 18:14:59 , should result 30% 日期在2016-04-15 14:00:00 : 2018-01-25 18:14:59之间的结果应为30%

example: 例:

Query to this table for date 2016-01-10 08:00:00 should result 50% 查询此表以获取日期2016-01-10 08:00:002016-01-10 08:00:00 50%

I have searched through SO & Google but couldn't find a solution for my case; 我已经搜索了SO和Google,但找不到适合我的案例的解决方案;

Tried a query for my example like 尝试查询我的示例,例如

SELECT * FROM discounts WHERE date<='2016-01-10' AND time<='08:00:00'
ORDER BY date DESC LIMIT 1

but no luck! 但没有运气!

Any help is really appreciated. 任何帮助都非常感谢。

You could use something like this for your table structure - 您可以在表结构中使用类似的内容-

SELECT discount FROM discounts WHERE CAST(CONCAT(date, “ “, time) AS DATETIME) BETWEEN “2015-08-10 09:30:00” AND “2016-04-15 13:59:59” 从“ 2015-08-10 09:30:00”和“ 2016-04-15 13:59:59”之间的CAST(CONCAT(date,““,time)AS DATETIME))中选择折扣

You might be able to get away without casting the values but this will ensure your date and time values are correctly formatted. 您也许可以不用强制转换值就可以摆脱困境,但这可以确保日期和时间值的格式正确。

However I would suggest storing the date and time values as a single standard datetime value. 但是,我建议将日期和时间值存储为单个标准datetime值。 Is there a reason why you have it as two separate columns? 您为何将其作为两个单独的列?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM