php - codeigniter 数据库类 JOIN USING

标签 php mysql codeigniter

我该如何使用 使用(table.id)左连接Table2

我的代码示例

$this->db->select('visits.*,patients.name,workers.dr_name,time(visits.time)');
$this->db->from('visits');
//The next join = LEFT JOIN workers ON visits.worker_id=workers.worker_id
$this->db->join('workers','visits.worker_id=workers.worker_id','left');//WORKING
//The next join = JOIN `patients` ON patient_id --> i want it JOIN patients USING(patient_id)
$this->db->join('patients','patient_id','USING');//NOT WORKING

我搜索了所有,但找不到解决方案,所以我打开并尝试编辑 db_active_rec.php 中的 JOIN 函数

/system/database/DB_active_rec.php

并找到了 join 函数

public function join($table, $cond, $type = '')
    {
        if ($type != '')
        {
            $type = strtoupper(trim($type));

            if ( ! in_array($type, array('LEFT', 'RIGHT', 'OUTER', 'INNER', 'LEFT OUTER', 'RIGHT OUTER')))
            {
                $type = '';
            }
            else
            {
                $type .= ' ';
            }
        }

        // Extract any aliases that might exist.  We use this information
        // in the _protect_identifiers to know whether to add a table prefix
        $this->_track_aliases($table);

        // Strip apart the condition and protect the identifiers
        if (preg_match('/([\w\.]+)([\W\s]+)(.+)/', $cond, $match))
        {
            $match[1] = $this->_protect_identifiers($match[1]);
            $match[3] = $this->_protect_identifiers($match[3]);

            $cond = $match[1].$match[2].$match[3];
        }

        // Assemble the JOIN statement
            $join = $type.'JOIN '.$this->_protect_identifiers($table, TRUE, NULL, FALSE).' ON '.$cond;  


        $this->ar_join[] = $join;
        if ($this->ar_caching === TRUE)
        {
            $this->ar_cache_join[] = $join;
            $this->ar_cache_exists[] = 'join';
        }

        return $this;
    }

尝试编辑“//组装JOIN语句”下的部分,并放置if条件来检测USING,然后相应地调整查询,但失败了。史诗般的失败

有人可以帮忙吗?我如何编辑此函数,以便它在连接查询中使用 USING ?

最佳答案

来自the manual :

$this->db->join();

允许您编写查询的 JOIN 部分:

$this->db->select('*');
$this->db->from('blogs');
$this->db->join('comments', 'comments.id = blogs.id');

$query = $this->db->get();

// Produces: 
// SELECT * FROM blogs
// JOIN comments ON comments.id = blogs.id

如果您需要在一个查询中进行多个联接,则可以进行多个函数调用。

如果您需要特定类型的 JOIN,您可以通过函数的第三个参数指定它。选项有:左、右、外、内、左外、右外。

$this->db->join('comments', 'comments.id = blogs.id', 'left');

// Produces: LEFT JOIN comments ON comments.id = blogs.id

关于php - codeigniter 数据库类 JOIN USING,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13730236/

相关文章:

php - 无法在 mysql 数据库中存储 stripe webhook 数据

PHP ActiveRecord 似乎没有使用我的自定义属性

mysql - 将日期输入数据库(phpMyAdmin、SQL)

php - 带有多个可选搜索词的参数化查询

php - Apache 奇怪地处理字符

php - Codeigniter 设置横向数据库过滤器

php - CakePHP 外壳单元测试

php - 提取 Zip 内的目录

php - 如何在 PHP 中转换(非常)旧的日期?

codeigniter - 与 codeigniter 和backbone.js 的数据库交互