SQL selecting from two tables returns duplicate values - Codeigniter SQL selecting from two tables returns duplicate values - Codeigniter codeigniter codeigniter

SQL selecting from two tables returns duplicate values - Codeigniter


This is normal because of the implicit join you made! Why don't you simply request two queries, one per table, and then merge the results in one array?

public function getcentrelist(){    $this->load->database();    $query_courses=  $this->db->query('SELECT course_name as name from tbl_training_courses');      $query_centers=  $this->db->query('SELECT centre_name as name from tbl_traning_centres');     $courses = $query_courses->result();    $centers = $query_centers->result();    return array_merge($courses,$centers);}

Note please that I have renamed the fields course_name and center name to a unified name: "name", this is necessary to have a coherent merged table.


Use DISTINCT

public function getcentrelist(){    $this->load->database();    $query=  $this->db->query('SELECT DISTINCT centre_name,course_name from tbl_training_courses, tbl_traning_centres GROUP BY center_name');     return $query->result();}

or use Group By

public function getcentrelist(){    $this->load->database();    $query=  $this->db->query('SELECT centre_name,course_name from tbl_training_courses, tbl_traning_centres GROUP BY center_name');     return $query->result();}


The data returns by your query is normal because you select One line and you fetch all lines of the second table so if you have 10 lines in the second line you will get each value 10 times and if you even put distinct you will get a problem. To avoid such a problem you need to use condition or Join between two tables.