我正在寻找查询结果,我只能看到表2中没有的表1数据;这是我的表定义和数据;
表1
id name father name age
1 a a father 60
2 b b father 70
3 c c father 60
4 d d father 50
5 e e father 20
6 f f father 32
7 g g father 40
表2
id account_amount
1 42
3 90
5 80
7 49
现在我希望表1中的所有记录在表2中不可用或表2中的对应account_amount小于50.这里将是所需的输出
id name father name age
1 a a father 60
2 b b father 70
4 d d father 50
6 f f father 32
7 g g father 40
提前感谢codeigniter中的解决方案查询
答案 0 :(得分:2)
使用反连接:
SELECT t1.id, t1.name, t1.father_name, t1.age
FROM table1 t1
LEFT JOIN table2 t2
ON t1.id = t2.id AND t2.account_amount >= 50
WHERE t2.id IS NULL
不存在:
SELECT t1.id, t1.name, t1.father_name, t1.age
FROM table1 t1
WHERE NOT EXISTS
(SELECT 1 FROM table2 t2 WHERE t2.id = t1.id AND t2.account_amount >= 50)
由于您使用MySQL标记了问题,因此第一个选项会提高性能。
在模型中
$this->db->query("SELECT t1.id, t1.name, t1.father_name, t1.age
FROM table1 t1
LEFT JOIN table2 t2
ON t1.id = t2.id AND t2.account_amount >= 50
WHERE t2.id IS NULL");
Imo Active Record对此类查询不方便
答案 1 :(得分:1)
你在这里:
$this->db->select('id');
$excludedData = $this->db->get('table2')->result_array();
foreach($excludedData as $key => $record){
$excludedData[$key] = $record['id'];
}
$this->db->where_not_in('id',$excludedData);
$desiredData = $this->db->get('table1')->result_array();