2013-04-18 47 views
1

我已经使用以下查询从表格中选择行。选择不在其他表格中的记录

Table 1: 

id description status add_date topicid 
1 xyz   0  22-3-13  5 
2 pqr   0  21-3-13  5 
3 abc   0  20-3-13  5 
4 sdd   0  22-3-13  5 


Table2: 

id  otherid  
1  2 
2  3 

此查询为我提供了来自table1的所有记录,但我想选择那些不在table2中的记录。
像table1'id'在table2'otherid'中不存在。
在我的情况下,想要从table1中选择id 1和4的记录。因为它不存在于table2中作为'otherid'。

$topicid = 5; 

$q =$this->db->select(array(
      't1.id as id', 
      't1.description', 
      't1.topicid', 
      't1.add_date')) 
      ->from('table1 AS t1') 
      ->where('t1.topicid',$topicid) 
      ->where('t1.status',0) 
      ->order_by('t1.add_date DESC)->get(); 
+0

SELECT * FROM表1 .t1其中t1.topicid = $ topicid和ti.status = 0和不t1.id(选择T2。从表2的顶部t2,表1作为t1其中t2.otherid = t1.id)也许这将有助于 –

回答

2

尝试此查询将工作

$topicid = 5; 

$q =$this->db->select(array(
      't1.id as id', 
      't1.description', 
      't1.topicid', 
      't1.add_date')) 
      ->from('table1 AS t1') 
      ->where('t1.topicid',$topicid) 
      ->where('t1.status',0) 
      ->where('t1.id NOT IN (select otherid from table2)',NULL,FALSE) 
      ->order_by('t1.add_date DESC)->get(); 
+0

我用这个答案,谢谢。 –

+0

好工作,希望你喜欢它。 – umefarooq

0
$select = array(
       't1.id as id', 
       't1.description', 
       't1.topicid', 
       't1.add_date' 
      ); 
$this->db 
     ->select($select) 
     ->join('Table2','Table2.otherid = Table1.id','left') 
     ->where('Table2.otherid IS','NULL') 
     ->where('Table1.topicid',$topicid) 
     ->where('Table1.status',0) 
     ->get('Table1'); 
相关问题