使用Codeigniter的复杂查询联接

时间:2018-08-11 09:28:26

标签: php mysql codeigniter codeigniter-3 codeigniter-2

我有一个查询,该查询在phpmyadmin中产生结果,但在codeigniter中不产生结果。

$sql = "SELECT express_interests.*, 
       cl_to  .User_Name AS ToClient, 
       cl_from.User_Name AS FromClient,
       cl_from.Member_Id AS FromMid,
       cl_to.Member_Id AS ToMid

FROM express_interests  
    INNER JOIN users AS cl_to ON cl_to.User_Id = express_interests.To_Id
    INNER JOIN users AS cl_from ON cl_from.User_Id = express_interests.User_Id";

我想在codeignitor中使用相同的查询。这就是我用过的

$this->db->select('express_interests.*, 
       cl_to  .User_Name AS ToClient, 
       cl_from.User_Name AS FromClient,
       cl_from.Member_Id AS FromMid,
       cl_to.Member_Id AS ToMid
');

$this->db->from('express_interests');


$this->db->join('users AS cl_to', 'cl_to.User_Id = express_interests.To_Id');
$this->db->join('users AS cl_from', 'cl_from.User_Id = express_interests.User_Id');

当我使用它时会说

  

“字段列表”中的未知列“ cl_to .User_Name”

在codeigniter中使用上述查询的正确方法是什么。

2 个答案:

答案 0 :(得分:0)

# some other imports #

from django.contrib import messages

    # some other codes # 

def oxford(request):
    search_result = {}
    if 'word' in request.GET:
        form = DictionaryForm(request.GET)
        if form.is_valid():
            search_result = form.search()
            messages.success(request, 'Your query is successful!')
        else:
            messages.warning(request, 'form is not valid.')
    else:
        form = DictionaryForm()
        messages.warning(request, 'Please correct the error.')
    return render(request, 'products/oxford.html', {'form': form, 'search_result': search_result})

替换为

$this->db->select('express_interests.*, 
       cl_to  .User_Name AS ToClient, 
       cl_from.User_Name AS FromClient,
       cl_from.Member_Id AS FromMid,
       cl_to.Member_Id AS ToMid
');

表别名和列名之间不需要的空格

答案 1 :(得分:0)

替换

cl_to  .User_Name AS ToClient,

使用

cl_to  .User_Name AS ToClient,

或者您可以直接在codeigniter中运行sql语句

$sql = "SELECT express_interests.*, 
   cl_to  .User_Name AS ToClient, 
   cl_from.User_Name AS FromClient,
   cl_from.Member_Id AS FromMid,
   cl_to.Member_Id AS ToMid

FROM express_interests  
INNER JOIN users AS cl_to ON cl_to.User_Id = express_interests.To_Id
INNER JOIN users AS cl_from ON cl_from.User_Id = express_interests.User_Id"; 

$result=$this->db->query($sql);

print_r($result->result());

die;