codeigniter中表别名中的问题

时间:2015-06-17 13:08:02

标签: mysql codeigniter alias

这里,我正在为内部选择创建一个别名,但它会自动将表前缀添加到别名表中。我的SQL查询如下:

SELECT
    `tb1`.*, `tb2`.*, `tb3`.`client_name`,
    `cms_tb4`.*,  `tb1`.`project_status` AS pstat
FROM
    (`cms_projects` tb1)
JOIN  `cms_project_type` tb2 ON `tb2`.`id` = `tb1`.`project_type`
JOIN  `cms_clients` tb3 ON `tb1`.`client_id` = `tb3`.`client_id`
JOIN  (
    SELECT
        *
    FROM
        (
            SELECT
                t1.project_id AS projid,
                 t2.work_id,
                t2.work_date
            FROM
                cms_projects_mod t1,
                cms_work_status_emp  t2
            WHERE
                t1.module_id = t2.pro_module_id
            ORDER BY
                t2.work_date DESC
        )  AS subtb4
    GROUP BY
        projid
    ORDER BY
        work_date DESC
) AS tb4 ON  `cms_tb4`.`projid` = `tb1`.`project_id`
LIMIT 50

我正在研究codeigniter框架。

在codeigniter模型中

就像这样

         $this->db->select('tb1.*');
                $this->db->select('tb1.project_status as pstat');
                $this->db->from('cms_projects tb1');
               $this->db->join('project_type tb2', 'tb2.id=tb1.project_type');
             $this->db->join('clients tb3', 'tb1.client_id = tb3.client_id');
            $this->db->join("(
                       select * from (
              select t1.project_id as projid,                                     t2.work_id,t2.work_date from cms_projects_mod t1, cms_work_status_emp t2  where  t1.module_id = t2.pro_module_id order by  t2.work_date desc) as subtb4 
 group by  projid  order by  work_date desc ) as tb4 ",
"tb4.projid = tb1.project_id" ,false);
      $this->db->group_by("tb1.project_id");
            $this->db->order_by("tb3.work_date",'desc');

这里我没有在第三次加入tb4中给出任何前缀,但CI在运行时自动添加。

2 个答案:

答案 0 :(得分:1)

请检查CodeIgniter文档中的代码顺序。

$this->db
   ->select()
   ->from()
   ->join()

这是正确的顺序。更改顺序有时会导致复杂查询中的问题。

访问此链接https://github.com/bcit-ci/CodeIgniter/issues/2975

答案 1 :(得分:-1)

为什么使用查询字符串?如果你使用coeignoter为什么不使用活动记录。使用sql注入自动保护Active Record查询。  你可以做到这一点....它不一样你只想知道如何使用活动记录sql。

$query = $this->db->select('*',FALSE)
                  ->from('tb1','tb2'.....)
                  ->join('tb2', 'tb1.cms_project_type = tb2.cms_project_type','left')
                  ->join('tb3', 'tb1.cms_project_type = tb2.cms_project_type','left')
                  ->group_by('projid')  
                  ->order_by('work_date','DESC') 
                  ->get();

https://ellislab.com/codeigniter/user-guide/database/queries.html

希望得到这个帮助。