如何计算 CodeIgniter 中某一年日期的行数?

How to count the number of rows with a date from a certain year in CodeIgniter?

我有以下查询。

$query = $this->db->query('SELECT COUNT(*) FROM iplog.persons WHERE begin_date LIKE '2014%'');

我需要计算 2014 年中带有 begin_date 的列数。

当我 运行 这个脚本时,我收到一个错误:

Parse error: syntax error, unexpected '2014' (T_LNUMBER) in C:\xampp\htdocs\iPlog2\application\controllers\stat.php on line 12

我试图将我的 CI 脚本更改为

$query = $this->db->query('SELECT COUNT(*) FROM iplog.persons WHERE begin_date LIKE "2014%"');

但它导致了一个错误。

像这样替换引号:

$query = $this->db->query("SELECT COUNT(*) FROM iplog.persons WHERE begin_date LIKE '2014%'");

双引号你的整个查询,然后简单地引用你的 LIKE 标准。

你的意思是,计算 ROWS:

为此,只需根据条件计算您拥有的行数:

$year = '2014'
$this->db->from('iplog');
$this->db->like('begin_date', $year); 
$query = $this->db->get();
$rowcount = $query->num_rows();

首先,关于单引号的使用,您有一个简单的拼写错误。您的完整 sql 字符串应该用双引号引起来,以便您的 value-quoting 可以用单引号引起来。

其次,您使用了不恰当的查询逻辑。当你想对 DATE 或 DATETIME 类型的列进行比较时,你永远不应该使用 LIKE。有特定的 MYSQL 函数专门用于处理这些类型。在您的情况下,您应该使用 YEAR() 来隔离 begin_date 值的年份部分。

资源:https://www.w3resource.com/mysql/date-and-time-functions/mysql-year-function.php

您可以这样编写原始查询:(COUNT(*)COUNT(1) 是等价的)

$count = $this->db
              ->query("SELECT COUNT(1) FROM persons WHERE YEAR(begin_date) = 2014")
              ->row()
              ->COUNT;

或者,如果您想使用 Codeigniter 方法来构建查询:

$count = $this->db
              ->where("YEAR(begin_date) = 2014")
              ->count_all_results("persons");

您可以 return 所有符合条件的行中的所有值,但这意味着向数据库询问您无意使用的值——这不是最佳做法。 我不推荐以下:

$count = $this->db
              ->get_where('persons', 'YEAR(begin_date) = 2014')
              ->num_rows();

因此,当您无意使用结果集中的值时,不应生成完全填充的结果集然后调用 num_rows()count()