【问题标题】:How to count the number of rows with a date from a certain year in CodeIgniter?如何在 CodeIgniter 中计算某一年日期的行数?
【发布时间】:2015-02-26 14:02:37
【问题描述】:

我有以下问题。

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

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

运行此脚本时出现错误:

解析错误:语法错误,第 12 行 C:\xampp\htdocs\iPlog2\application\controllers\stat.php 中出现意外的 '2014' (T_LNUMBER)

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

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

但它导致了错误。

【问题讨论】:

    标签: sql codeigniter


    【解决方案1】:

    你的意思是,计算行数:

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

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

    【讨论】:

      【解决方案2】:

      像这样替换引号:

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

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

      【讨论】:

        【解决方案3】:

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

        其次,您使用了不适当的查询逻辑。当你想对 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");
        

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

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-06-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-01-13
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多