简体   繁体   中英

Mysql group_concat query gives error

I have get this error You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' ) ) AS name FROM ( resource_details ) JOIN location ON reso_dtail_location`' at line 3

Code as follows

  $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();

Change your query like below

$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();

Two changes from your existing query add false in select statement and where condition is wrong and also used the alias where you have two many joins in a single query.

Note : I have added alias as per my understanding you can change it as per your database structure

For adding a query in from clause

$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');

remember if you want to add join above query than use **ft* for alias

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM