【问题标题】:How to CREATE a 'VIEW(SQL)' in CodeIgniter and SELECT data from it?如何在 CodeIgniter 中创建“视图(SQL)”并从中选择数据?
【发布时间】:2013-04-27 15:57:28
【问题描述】:

我有一个查询需要在将记录包含在查询中之前检查它是否仍然处于活动状态。现在我的问题是该记录的记录状态在另一个数据库中,我们都知道我们不能连接来自不同数据库的表。

我想做的是从另一个数据库创建一个视图,然后将该视图加入到我的查询中。问题是如何在 CodeIgniter 中创建视图并从中选择数据?

提前致谢。

顺便说一句,我不是设计数据库的人。 -公司定义-

这是我的查询示例,它不是确切的示例,因为它包含很多表。我希望我能给你一些我正在尝试做的事情的提示。

SELECT count(IDNO), course, sum(student_balance)
FROM student_balances
WHERE school_term = '2013' AND student_balance > 0
GROUP BY course
ORDER BY course

无论是否注册,都会选择那里的所有学生记录。有一个表格,其中包含当前学年注册学生,该表格来自另一个数据库。我只想统计已注册学生的记录。

【问题讨论】:

  • 我有点困惑,视图需要在单独的数据库上创建并转移到另一个数据库吗?
  • @Paw Cabelin - 我更新了我的答案,因为您添加了查询详细信息。

标签: php sql codeigniter ms-access sql-view


【解决方案1】:

我们都知道我们不能连接来自不同数据库的表

不确定是否适用于您的情况,但这里有一些关于跨数据库查询的帖子:

Querying multiple databases at once
PHP Mysql joins across databases
https://stackoverflow.com/a/5698396/183254

无论如何,您不需要使用连接;只需查询其他数据库以查看该事物是否处于活动状态

$DB2 = $this->load->database('otherdb', TRUE);
$active = $DB2->query('SELECT is_active blah...');
if($active)
{
    //do other query
}

更新

这可能在语法上不正确,但应该为您指明正确的方向。一如既往,user guide

// load other db
$db2 = $this->load->db('otherdb',TRUE);

// get enrolled student id's from other db
$active_students = $db2->query('SELECT id FROM students WHERE enrolled = 1')->result();

// query this db for what you want
$this->db->select('count(IDNO), course, sum(student_balance)');
$this->db->where('school_term',2013);
$this->db->where('student_balance >',0);

// where_in will limit the query to the id's in $active_students
$this->db->where_in('id', $active_students);

// finally, execute the query on the student_balances table
$balances = $this->db->get('student_balances');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-16
    • 2021-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    • 1970-01-01
    相关资源
    最近更新 更多