我使用以下查询从表中选择行。
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中的记录 比如table2'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 :(得分: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();
答案 1 :(得分: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');