我有一个使用CodeIgniter和数据表生成的查询。
查询如下:
SELECT `tbl_leads`.*, t2`.`username` as `namexx`
FROM `tbl_leads`
JOIN `tbl_users` AS `t2` ON `t2`.`user_id` = JSON_UNQUOTE(JSON_EXTRACT(JSON_KEYS(tbl_leads.permission), '$[0]'))
WHERE (
`tbl_leads`.`lead_name` LIKE '%d%' ESCAPE '!'
OR `tbl_leads`.`contact_name` LIKE '%d%' ESCAPE '!'
OR `tbl_leads`.`email` LIKE '%d%' ESCAPE '!'
OR `tbl_leads`.`phone` LIKE '%d%' ESCAPE '!'
OR `tbl_leads`.`lead_status_id` LIKE '%d%' ESCAPE '!'
OR `tbl_leads`.`permission` LIKE '%d%' ESCAPE '!'
OR `t2`.`username` LIKE '%d%' ESCAPE '!'
OR `tbl_leads`.`linkedin` LIKE '%d%' ESCAPE '!'
OR `tbl_leads`.`leads_id` LIKE '%d%' ESCAPE '!'
)
AND `converted_client_id` = '0'
ORDER BY `leads_id` DESC
LIMIT 20
此查询是根据POST搜索请求生成的。
如果您还没有猜到,我会得到
“ where子句”中的未知列“ t2.username”
因为在where查询中无法识别列别名(tbl_users.username
也不会更改)。
我正在通过next(数据表模型)生成它:
if ($this->table == 'tbl_leads') {
$this->db->select ('tbl_leads.*, t2.username as namexx');
$this->db->join("tbl_users AS t2", "t2.user_id = JSON_UNQUOTE(JSON_EXTRACT(JSON_KEYS(tbl_leads.permission), '$[0]'))", "LEFT");
}
$query = $this->db->get();
我还编辑了搜索功能,以便按如下方式获取表指针(我知道这不是一个好习惯,而且是多余的):
foreach ($this->column_search as $item) // loop column
{
if ($_POST['search']['value']) // if datatable send POST for search
{
if ($i === 0) // first loop
{
$this->db->group_start(); // open bracket. query Where with OR clause better with bracket. because maybe can combine with other WHERE with AND.
if($this->table=='tbl_leads'){
if( $item=='namexx'){
$this->db->like('tbl_users.username', $_POST['search']['value']);
}else{
$this->db->like($this->table.'.'.$item, $_POST['search']['value']);
}
}else{
$this->db->like($item, $_POST['search']['value']);
}
} else {
if($this->table=='tbl_leads'){
if( $item=='namexx'){
$this->db->or_like('tbl_users.username', $_POST['search']['value']);
}else{
$this->db->or_like($this->table.'.'.$item, $_POST['search']['value']);
}
}else{
$this->db->or_like($item, $_POST['search']['value']);
}
}
if (count($this->column_search) - 1 == $i) //last loop
$this->db->group_end(); //close bracket
}
$i++;
}
答案 0 :(得分:0)
修改您的查询,从连接语句中删除t2
别名,如下所示:
if ($this->table == 'tbl_leads') {
$this->db->select ('tbl_leads.*, tbl_users.username as namexx');
$this->db->join("tbl_users", "tbl_users.user_id = JSON_UNQUOTE(JSON_EXTRACT(JSON_KEYS(tbl_leads.permission), '$[0]'))", "LEFT");
}
$query = $this->db->get();