简体   繁体   English

类型为VARCHAR时的SQL查询日期

[英]SQL Query On Date When Type Is VARCHAR

I'm trying to query a database with a between 2 dates... The problem is the column that I am querying contains dates that are currently formatted like this "01/01/2014" (dd/mm/yyyy) with a column type of VARCHAR. 我正在尝试使用两个日期查询数据库...问题是我查询的列包含当前格式为“01/01/2014”(dd / mm / yyyy)的日期,其中包含一列VARCHAR的类型。

At the moment, I can't convert the column to a date type. 目前,我无法将列转换为日期类型。

Basically when I query the table because it's not set to date type the between query doesn't return the correct rows... 基本上当我查询表因为它没有设置为日期类型时,查询之间没有返回正确的行...

Has anyone else come across this problem, is there something I can change within the query? 有没有其他人遇到过这个问题,我可以在查询中更改一些内容吗?

$this->db->where('IssueDate >=', '02/12/2013');
$this->db->where('IssueDate <=', '22/01/2014');
$query = $this->db->get('MYTABLE');

Thanks guys. 多谢你们。

The solution is to use str_to_date() : 解决方案是使用str_to_date()

$this->db->where("str_to_date(IssueDate, '%d/%m/%Y') >=", "'2013-12-92'");
$this->db->where("str_to_date(IssueDate, '%d/%m/%Y') <=", "'2014-01-22'");
$

You may not have any control over the database. 您可能无法控制数据库。 But you do have control over your own constants. 但是你可以控制自己的常量。 You should get used to the ISO standard YYYY-MM-DD for such constants -- unambiguous and accepted correctly by most databases. 您应该习惯ISO标准YYYY-MM-DD这样的常量 - 大多数数据库都是明确无误的。

I might suggest creating a view on the table in the database that transforms the string date columns you have into the following format... YYYYMMDD 我可能会建议在数据库中的表上创建一个视图,该视图将您拥有的字符串日期列转换为以下格式... YYYYMMDD

That format is sortable and can easily be compared versus other similar formatted dates - you can even do date arithmetic with it. 该格式是可排序的,可以轻松地与其他类似的格式化日期进行比较 - 您甚至可以使用它进行日期算术。

Keep in mind that a view does not copy the table or add any performance overhead. 请记住,视图不会复制表或添加任何性能开销。 It is often a good idea to access any table through a view even if initially you do not need to perform any manipulations on the underlying table - it will help if you later find you do need to perform them. 通过视图访问任何表通常是一个好主意,即使最初您不需要对基础表执行任何操作 - 如果您以后发现需要执行它们将会有所帮助。

use BETWEEN clause with STR_TO_DATE() . BETWEEN子句与STR_TO_DATE()一起使用 Check below code:- 检查以下代码: -

$wh = STR_TO_DATE(`IssueDate`,'%d/%m/%Y')." between '02/12/2013' and '22/01/2014'";
$this->db->where($wh);

Expect it'll give You perfect result. 期待它能给你完美的结果。

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

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