在Codeigniter中使用查询生成器-如何正确别名?

时间:2019-02-01 06:25:40

标签: mysql sql codeigniter

我已经在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

1 个答案:

答案 0 :(得分:1)

这不是MySQL的工作方式不是codeigniter的问题,不是字段名(请避免使用这种字段名) 它的功能和选择或调用功能与定义它不同,因此您必须以与选择它相同的方式放置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