【问题标题】:Sql Join in Codeigniter?Sql加入Codeigniter?
【发布时间】:2015-03-06 22:49:55
【问题描述】:

我想将此查询转换为 codeigniter,但最后一行 - 'not in' 不起作用 (我想要分配表中没有的测试)

SELECT * FROM (`tests` AS A) 
INNER JOIN `test_types` AS B ON `A`.`tst_test_type_id` = `B`.`tt_id` 
INNER JOIN `app_types` AS C ON `A`.`tst_app_type_id` = `C`.`at_id`
 AND tst_id not in (select ast_test_id from assigned_tests)

到目前为止我尝试了什么

  $this->db->select('*');
    $this->db->from('tests AS A');// I use aliasing make joins easier
    $this->db->join('test_types AS B', 'A.tst_test_type_id = B.tt_id', 'INNER');
    $this->db->join('app_types AS C', 'A.tst_app_type_id = C.at_id', 'INNER');
    $this->db->join('assigned_tests AS D', 'A.tst_id = D.ast_test_id', 'outer');

【问题讨论】:

    标签: jquery mysql sql codeigniter join


    【解决方案1】:

    从你说的“将此查询转换为 codeigniter”的问题,但事实并非如此,您应该说“转换为活动记录”,实际上 codeigniter 可以使用活动记录类,或者它也可以使用本机查询,它们使用的资源少于我从doc 引用的活动记录

    注意:如果您打算编写自己的查询,您可以禁用此功能 数据库配置文件中的类(活动记录),允许核心数据库库 和适配器以使用更少的资源。

    所以为了简短起见,您可以像这样使用您的查询:

    $qry = $this->db->query('SELECT * FROM (`tests` AS A) 
    INNER JOIN `test_types` AS B ON `A`.`tst_test_type_id` = `B`.`tt_id` 
    INNER JOIN `app_types` AS C ON `A`.`tst_app_type_id` = `C`.`at_id`
    AND tst_id not in (select ast_test_id from assigned_tests)');
    
    return $qry->result();
    

    【讨论】:

      【解决方案2】:

      您可以通过将转义标志设置为false,将子查询作为参数提交。

      $this->db->select('*');
      $this->db->from('tests AS A');
      $this->db->join('test_types AS B', 'A.tst_test_type_id = B.tt_id', 'INNER');
      $this->db->join('app_types AS C', 'A.tst_app_type_id = C.at_id', 'INNER');
      $this->db->join('assigned_tests AS D', 'A.tst_id = D.ast_test_id', 'outer');
      $this->db->where('tst_id not in', '(select ast_test_id from assigned_tests)', false);
      

      【讨论】:

      • 有没有办法避免这种“从assigned_tests中选择ast_test_id”,因为这会带来大量数据
      【解决方案3】:

      我发现这与 IS NULL 一起使用 - 如果有一些更普通的东西,请发布

      $this->db->select('*');
              $this->db->from('tests AS A');
              $this->db->join('test_types AS B', 'A.tst_test_type_id = B.tt_id', 'INNER');
              $this->db->join('app_types AS C', 'A.tst_app_type_id = C.at_id', 'INNER');
              $this->db->join('assigned_tests AS D', 'A.tst_id = D.ast_test_id', 'left');
              $this->db->where('D.ast_test_id IS NULL');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-11
        • 2013-01-19
        相关资源
        最近更新 更多