Mysql group_concat查询给出错误

时间:2016-06-30 07:30:33

标签: php mysql sql codeigniter

我收到此错误 您的SQL语法中有错误;查看与您的MySQL服务器版本对应的手册,以便在第3行“) ) AS name FROM ( resource_details ) JOIN位置ON reso_dtail_location”附近使用正确的语法

代码如下

  $this->db->select('loc_country,CONCAT(s_name , ":", GROUP_CONCAT( DISTINCT dist_name
    ORDER BY dist_name ASC
    SEPARATOR "," ) ) AS name ');


  $this->db->from('resource_details');
            //join
            $this->db->join('location','reso_dtail_location=loc_id');        
            $this->db->join('go_state', 'go_stste_id = loc_state', 'left');
            $this->db->join('go_country', 'num = loc_country', 'left');
            $this->db->join('go_dist', 'id = loc_district', 'left');
            $this->db->where('loc_id !=1 AND loc_id !=2');
            $this->db->group_by('country_name');
            $query = $this->db->get();

1 个答案:

答案 0 :(得分:1)

更改您的查询,如下所示

$this->db->select('loc_country,CONCAT(s_name , ":", GROUP_CONCAT( DISTINCT dist_name ORDER BY dist_name ASC SEPARATOR "," )) AS name',false);
$this->db->from('resource_details rd');
            //join
            $this->db->join('location l','rd.reso_dtail_location=l.loc_id');        
            $this->db->join('go_state gs', 'gs.go_stste_id = l.loc_state', 'left');
            $this->db->join('go_country gc', 'gc.num = l.loc_country', 'left');
            $this->db->join('go_dist gd', 'gd.id = l.loc_district', 'left');
            $this->db->where('l.loc_id !=',1);
$this->db->where('l.loc_id !=',2);
            $this->db->group_by('gc.country_name');
            $query = $this->db->get();

现有查询中的两项更改在选择语句中添加false 其中条件错误,并且还使用了在单个查询中有两个连接的别名。< / p>

注意:根据我的理解,我添加了别名,您可以根据数据库结构更改别名

用于从子句

添加查询
$this->db->_protect_identifiers=false;    
$this->db->select('ft.id,GROUP_CONCAT(ft.Name separator ",") as ColumnName',false);
    $this->db->from('(select id, concat(Name, ":", GROUP_CONCAT(Value separator ",")) as Name from mytbl group by id, Name) ft');
    $this->db->group_by('ft.id');

请记住,如果要在查询之上添加联接,请使用** ft *作为别名