selecting values from two tables using union but with different key

寵の児 提交于 2020-01-25 12:56:40

问题


I have two tables: teacher-record and student-record.

teacher-record has two columns: teacher_id, email (email of teacher)
student-record has two columns: student_id, email (email of student)

I am trying to select teacher_id and student_id using single query by using a union.

This is the MySQL query I used (I am also using codeignitor).

public function get_std_tech_id($std_email, $tech_email)
{
    $query = $this->db->query("
        SELECT `student_id` AS std FROM `student-record` WHERE `email`= '$std_email'
        UNION ALL
        SELECT `teacher_id` AS tech FROM `teacher-record` WHERE `email` ='$tech_email'");
    return $query->result_array();
}

Now, the result array I get is this:

Array ( [std] => SID2016063(student_id) ) Array ( [std] => TECH20160922(teacher_id) )

What I am trying or get is like this:

Array ( [std] => SID2016063 ) Array ( [tech] => TECH20160922 )

How can I get a result like this?


回答1:


UNION won't allow you this, it needs same column name.

You can add a 2nd column containing what type of id that specific row contains:

SELECT `student_id` AS id, 'std' AS type FROM `student-record` WHERE `email`= '$std_email' 
UNION ALL 
SELECT `teacher_id` AS id, 'tech' AS type FROM `teacher-record` WHERE `email` ='$tech_email'

then in php you can differentiate the results based on the column type.

PS: I am not a PHP guy so I can't predict in what format this dataset will come.



来源:https://stackoverflow.com/questions/39498115/selecting-values-from-two-tables-using-union-but-with-different-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!