php - Codeigniter mysql 左连接包括选择

标签 php mysql codeigniter

如何将左连接包含选择转换为codeigniter sql方法?谢谢。我只是想知道。

SELECT c1.c1_id, c1.c1_name, c2.c2_id, c2.c2_name, c2.c2_type, c2.c2_status, f.f_id, f.f_name, f2.f2_id, f2.f2_name FROM category2 c2 
LEFT JOIN category1 c1 ON c1.c1_id = c2.c1_id 
LEFT JOIN (
    SELECT DISTINCT c2_id, f_id, f_name FROM file ORDER BY f_id DESC
) f ON f.c2_id = c2.c2_id
LEFT JOIN (
    SELECT DISTINCT c2_id, f2_id, f2_name FROM file2 ORDER BY f2_id DESC
) f2 ON f2.c2_id = c2.c2_id
WHERE c2.c2_status = 1
GROUP BY c2.c2_id

最佳答案

您可以使用 codeigniter 的子查询方式来执行此操作,为此您将不得不破解 codeigniter。像这样 转到 system/database/DB_active_rec.php 从这些函数中删除 public 或 protected 关键字

public function _compile_select($select_override = FALSE)
public function _reset_select()

现在可以写入子查询现在这是带有事件记录的查询

$select =   array('DISTINCT c2_id','f_id','f_name');
$this->db->select($select);
$this->db->from('file');
$this->db->order_by('f_id','DESC');
$subQuery1 = $this->db->_compile_select();

unset($select);

$this->db->_reset_select();

$select =   array('DISTINCT c2_id','f_id','f2_name');
$this->db->select($select);
$this->db->from('file2');
$this->db->order_by('f2_id','DESC');
$subQuery2 = $this->db->_compile_select();

unset($select); 

$this->db->_reset_select();

// And now your main query

$select =   array(
                  'c1.c1_id',
                  'c1.c1_name',
                  'c2.c2_id',
                  'c2.c2_name',
                  'c2.c2_type',
                  'c2.c2_status',
                  'f.f_id',
                  'f.f_name',
                  'f2.f2_id',
                  'f2.f2_name'
            );

$this->db->select($select);
$this->db->from('category2 c2');
$this->db->join("($subQuery1)",'f.c2_id = c2.c2_id','left');
$this->db->join("($subQuery2)",'f2.c2_id = c2.c2_id','left');
$this->db->where('c2.c2_status',1);
$this->db->group_by('c2.c2_id');
$main_query = $this->db->get();

事情就这样完成了。干杯!!! 注意:使用子查询时,您必须使用

$this->db->from('myTable')

而不是

$this->db->get('myTable')

运行查询。

现在,您可以检查已构建的查询

echo $this->db->last_query();

关于php - Codeigniter mysql 左连接包括选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15400938/

相关文章:

php - 如何解密 PHP 中 npm-rsa 创建的数据?

python - 尝试在试用 django 项目中下载 mysql 时出错

mysql - 需要有关谷歌地图过滤和将数据保存到数据库的建议

javascript - 在文本框中输入值时我需要调用一个函数

php - 将自定义变量添加到 Paypal 并行支付 IPN PHP

php - 从mysql中的多个表获取多个值?

php - Apache 不允许从网络上的其他设备访问

php - 在安装 PHP 时设置 MySQL 配置数据

codeigniter url参数交换

Php 财政年度报告,选择正确年份的麻烦