问题
I have a generated query using CodeIgniter and datatables.
The query looks like this:
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
This query gets generated on a POST request for search.
If you haven't already guessed, I'm getting
Unknown column 't2.username' in 'where clause`
because the column alias isn't recognized in the where query(neither does tbl_users.username
if it would be to change it).
I'm generating it through the next(datatables model):
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();
I also edited the search function so i get the table pointers as follows(I know its not a good practice and redundant):
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++;
}
回答1:
Modify your query, remove the t2
alias from the join statements like this :
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();
来源:https://stackoverflow.com/questions/56737364/php-mysql-unkown-column-in-where-join