gpt4 book ai didi

MySQL 日期时间比较

转载 作者:行者123 更新时间:2023-11-29 04:10:43 33 4
gpt4 key购买 nike

这是我的问题:

我的 mysql 数据库中有一个表,其中包含一些产品,它有两个名为“date_from”和“date_to”的列,它们确定产品处于事件状态的时间段。

在我的网站上有一个表单,管理员可以在其中选择两个日期时间值,如果产品的活跃期与管理员选择的跨度相交,则页面会更新产品列表。

这是我的查询,我用它来实现我想要的:

$sql="SELECT * FROM presents WHERE (date_from>".$date_from." AND date_to<".$date_to.") OR (date_from>".$date_from." AND date_to>".$date_to.") OR (date_from<".$date_from." AND date_to>".$date_to.") OR (date_from<".$date_from." AND date_to<".$date_to.")";

虽然我得到了这个错误:

mysql said: MySql error number: 1064 MySql error decription: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.26. 12:11:43 AND date_to<2012.07.30. 12:11:46) OR (date_from>2012.07.26. 12:11:' at line 1

有什么想法吗?

*编辑

我按照建议更改了查询并为变量添加了单引号。现在我没有收到错误,但查询似乎没有执行预期的操作 - 产品列表保持不变......现在是查询:

$sql="SELECT * FROM presents WHERE (date_from>'".$date_from."' AND date_to<'".$date_to."') OR (date_from>'".$date_from."' AND date_to>'".$date_to."') OR (date_from<'".$date_from."' AND date_to>'".$date_to."') OR (date_from<'".$date_from."' AND date_to<'".$date_to."')";

假设我的表中有这一行:

ID 名称 date_from date_to

1 次测试 2012-07-24 16:40:00 2012-07-31 16:40:00


我需要所有这些句点来返回行:

2012-07-23 16:40:00 至 2012-08-01 16:40:00

2012-07-23 16:40:00 至 2012-07-28 16:40:00

2012-07-26 16:40:00 至 2012-07-28 16:40:00

2012-07-26 16:40:00 至 2012-08-01 16:40:00

最佳答案

您需要引用您的变量。

但是最好不要concat sql,改用占位符。

关于MySQL 日期时间比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11647669/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com