简体   繁体   English

是否可以使用CodeIgniter使用多个数据库连接运行JOIN查询?

[英]Is it possible to run a JOIN query using multiple database connections using CodeIgniter?

Is it possible to join multiple tables from different databases using CodeIgniter's active record utilty? 是否可以使用CodeIgniter的活动记录实用程序连接来自不同数据库的多个表?

I understand that I have to create two separate database group in database.php and load them manually inside the model: 我知道我必须在database.php创建两个单独的数据库组,并在模型中手动加载它们:

$this->DB1= $this->load->database('somename1', TRUE);
$this->DB2= $this->load->database('somename2', TRUE);

However, I don't know how to use them join multiple tables from two separate databases. 但是,我不知道如何使用它们从两个单独的数据库连接多个表。

How can I accomplish this? 我怎么能做到这一点?

As far as I know, there is no way to do this using multiple database instances (ie your $DB1 and $DB2 variables). 据我所知,使用多个数据库实例(即$DB1$DB2变量)无法做到这一点。

However, if you have a user that has access to both databases, you can prefix your table names with the their database names, and it will work (at least with MySQL - I haven't tested anything else). 但是,如果您有一个可以访问这两个数据库的用户,则可以在表名前加上其数据库名称,并且它将起作用(至少使用MySQL - 我还没有测试任何其他内容)。 For example, this code: 例如,这段代码:

$this->load->database('first');
$this->db->select('*')->from('users');
$this->db->join('test.hometowns', 'users.id = second.hometowns.user');
$query = $this->db->get();

Will successfully run this query, returning the expected results: 将成功运行此查询,返回预期结果:

SELECT * 
FROM (`users`) 
JOIN `second`.`hometowns` ON `users`.`id` = `second`.`hometowns`.`user`;

Again, I've only tested this with MySQL, and other databases may have constraints regarding crossing database boundaries. 同样,我只用MySQL测试过这个,而其他数据库可能有关于跨越数据库边界的限制。 It also requires the user account to actually have permissions to read both databases/tables. 它还要求用户帐户实际上具有读取两个数据库/表的权限。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM