【问题标题】:Using Query Builder in Codeigniter - How to properly alias?在 Codeigniter 中使用查询生成器 - 如何正确别名?
【发布时间】:2019-02-01 06:25:39
【问题描述】:

我在 codeigniter 3.x 中使用查询生成器构建了以下查询

        $this->db->select('
            categories.*,
            posts.id,
            posts.category_id,
            posts.user_id,
            posts.updated_user_id,
            posts.title,
            posts.slug,
            posts.body,
            posts.post_image,
            year(posts.created_timestamp) as year, 
            month(posts.created_timestamp) as month
        ');

以上产生错误,'where 子句'中的未知列'year'。我已经转储了 sql 但根本无法弄清楚为什么 SQL 无法识别年份和月份?

SELECT 
    `categories`.*, 
    `posts`.`id`, 
    `posts`.`category_id`, 
    `posts`.`user_id`, 
    `posts`.`updated_user_id`, 
    `posts`.`title`, 
    `posts`.`slug`, 
    `posts`.`body`, 
    `posts`.`post_image`, 
     year(posts.created_timestamp) as year, 
     month(posts.created_timestamp) as month 
     FROM `posts` 
     JOIN `categories` ON `categories`.`id` = `posts`.`category_id` 
     WHERE 
        `year` = '2019' 
     AND `month` = '1' 
     LIMIT 5

【问题讨论】:

    标签: mysql sql codeigniter


    【解决方案1】:

    这不是 MySQL 工作方式的 codeigniter 问题 year 不是字段名称(请避免使用那种字段名称) 它是一个函数,选择或调用函数与定义它不同,因此您必须以与选择它相同的方式放置 where 子句。

    SELECT 
        `categories`.*, 
        `posts`.`id`, 
        `posts`.`category_id`, 
        `posts`.`user_id`, 
        `posts`.`updated_user_id`, 
        `posts`.`title`, 
        `posts`.`slug`, 
        `posts`.`body`, 
        `posts`.`post_image`, 
         year(posts.created_timestamp) as year, 
         month(posts.created_timestamp) as month 
         FROM `posts` 
         JOIN `categories` ON `categories`.`id` = `posts`.`category_id` 
         WHERE 
            year(posts.created_timestamp) = '2019' 
         AND month(posts.created_timestamp) = '1' 
         LIMIT 5
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-16
      • 1970-01-01
      • 1970-01-01
      • 2019-12-20
      相关资源
      最近更新 更多