0

Lets assume two tables:

STUDENTS:
id | name | faculty_id  

and:

FACULTIES:
id | name

I am trying to query for students by students.id and also return faculties.name where students.faculty_id = faculties.id.

I used:

SELECT students.*, faculties.name FROM students 
JOIN faculties on students.faculty_id = faculties.id
WHERE students.id = ' ... ';

This works well, however there is a problem:

If, by some mistake, the student was assigned a non-existent faculty_id than he would never be found. I would like to write more 'flexible' query that would return faculty.name only if match is found, otherwise just leave it empty.

Also, the query has to have no memory intensive loops, since you could query by name, etc... which results in large number of matches.

Dean
  • 7,814
  • 8
  • 30
  • 31

2 Answers2

2

A left join will return all students that meet your criteria whether or not student.faculty_id is associated with a valid faculty.id... the ifnull sets the value to blank if rather than "null"

    SELECT 
        students.*, 
        ifnull(faculties.name,'')
    FROM 
        students 
        LEFT JOIN faculties on students.faculty_id = faculties.id
    WHERE students.id = ' ... ';
dbinns66
  • 790
  • 6
  • 7
-3

Instead of JOIN in your query. Try INNER JOIN

SELECT students.*, faculties.name FROM students 
INNER JOIN faculties on students.faculty_id = faculties.id
WHERE students.id = ' ... ';
Jens
  • 67,715
  • 15
  • 98
  • 113
Brett Ezra
  • 121
  • 1
  • 11