3

我使用以下查询从表中选择行。

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();
4

2 回答 2

5

试试这个查询会起作用

$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();
于 2013-04-18T05:58:32.730 回答
1
$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');
于 2013-04-18T06:30:59.260 回答