【问题标题】:CodeIgniter activerecord how column = column in where clauseCodeIgniter activerecord how column = column in where 子句
【发布时间】:2016-01-25 21:56:37
【问题描述】:

我正在使用带有 activerecord 的 CodeIgniter 来访问我的数据库, 我想知道是否要编写这样的查询:

Select * from table1, table2
whher table1.id = table2.id

我试过了:

$where = array("table1.id" => "table2.id");     
$query = $this->db->get_where("table1, table2" , $where);   
return $query->result();

但它给了我一个错误,因为它编译为:

select * from table1, table2 
where table1.id = 'table2.id'

那么如何判断我想要一个列等于 codeIgniter 中 activerecord 中的另一列?

谢谢

【问题讨论】:

    标签: php sql codeigniter activerecord


    【解决方案1】:

    所以你可以试试这个

    $query = $this->db->query("SELECT * FROM table1 INNER JOIN table2 ON table1.id = table2.id WHERE table1.id = 25");
    $result = $query->result_array();
    return $result;
    

    有活动记录

    $this->db->select('*');
    $this->db->from('table1');
    $this->db->join('table2', 'table2.id = table1.id', 'inner');
    $this->db->where('table2.id', 007); 
    

    我在@Kisaragi 的回答中看到了你的Comment。不,你可以这样做。如果不将这些表连接在一起,您将无法从多个表中获取数据。

    【讨论】:

    • 谢谢,这个解决方案可行,但我想继续使用 activerecord 类而不是编写普通查询
    • 两个 CI 都定义了数学方法
    • @MohanadKaleia 立即查看
    • 好的,是的,看来这是唯一的解决方案
    • 我看到你的评论,但是我可以不使用普通的join来获取数据,比如:select * from table1, table2 where table1.id = table2.id 所以不需要使用join吧?跨度>
    【解决方案2】:

    我会改用连接子句

    $this->db->select('*');
    $this->db->join('table2 as t2','t2.id=t1.id');
    $this->db->get('table1 as t1');
    

    【讨论】:

    • 谢谢,这个方案也行,但是我不喜欢用很多join子句,奇怪的是where子句中没有比较两列的简单事情!
    • 您也可以使用having count > 1 子句。加入会更容易。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    • 1970-01-01
    • 1970-01-01
    • 2022-11-20
    • 2022-12-02
    • 1970-01-01
    • 2022-12-28
    相关资源
    最近更新 更多