Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"Syntax error or access violation" error while trying to join a table column multiple times

I want to join 3 tables named members, students and baseinfos.

And baseinfos holds some id as bas_id and name of it is stored in bas_value:

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

And this is my code:

$records = DB::table('members')
            ->where('mys_olp_id',4)
            ->join('students', 'members.mbr_usr_id', '=', 'students.std_mbr_id')
            ->join('baseinfos as gender', 'members.mbr_gender_id', '=', 'gender.bas_id as gvalue')
            ->join('baseinfos as degree', 'students.std_degree_id', '=', 'degree.bas_id as dvalue')
            ->select('gender.gvalue', 'degree.dvalue')
            ->get()->toArray();

But this is wrong and shows me this error:

SQLSTATE[42000]: Syntax error or access violation: 1064 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 `gvalue` inner join `baseinfos` as `degree`

Note that I can not say this:

$records = DB::table('members')
            ->where('my_students.mys_olp_id',4)
            ->join('students', 'members.mbr_usr_id', '=', 'students.std_mbr_id')
            ->join('baseinfos as degree', 'students.std_degree_id', '=', 'degree.bas_id')
            ->join('baseinfos as gender', 'members.mbr_gender_id', '=', 'gender.bas_id')
            ->select('gender.bas_value', 'degree.bas_value')
            ->get()->toArray();

Because degree.bas_value will overwrites gender.bas_value!

So how can I join these 3 tables properly?

>Solution :

Your aliase inside join does not formated correctly. I think you can achieve this in this way-

$records = DB::table('members')
            ->join('students', 'students.std_mbr_id', '=', 'members.mbr_usr_id')
            ->join('baseinfos as gender','gender.bas_id', '=', 'members.mbr_gender_id')
            ->join('baseinfos as degree','degree.bas_id' , '=', 'students.std_degree_id')
            ->where('mys_olp_id',4)
            ->select('gender.bas_id as gvalue', 'degree.bas_id as dvalue')
            ->get();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading