0

I have a query where I am getting the count of students. Now, I want to modify that query and manage it conditionally. Here is my query

SELECT count(students.id) AS student_count,
FROM students
LEFT JOIN students_admission ON students_admission.student_id = students.id
WHERE student_gender='Male'
AND students.address = 'Address'
GROUP BY id

This is what i want

$admission_date = null;

SELECT count(students.id) AS student_count,
FROM students
LEFT JOIN students_admission ON students_admission.student_id = students.id
WHERE student_gender='Male'
AND students.address = 'Address'
AND students_admission.admission_date = '$admission_date'
GROUP BY id

But, i want to add AND students_admission.admission_date = 'admission_date' this condition only when $admission_date is not null. So, I tried this

SELECT count(students.id) AS student_count,
FROM students
LEFT JOIN students_admission ON students_admission.student_id = students.id
WHERE student_gender='Male'
AND students.address = 'Address'
CASE WHEN '$admission_date' IS NOT NULL THEN students_admission.admission_date = '$admission_date' END
GROUP BY id

which returns a syntax error. How can I manage this?

GMB
  • 216,147
  • 25
  • 84
  • 135
Naina
  • 11
  • 2

1 Answers1

1

Just use boolean logic:

AND (
    :admission_date IS NULL 
    OR students_admission.admission_date = :admission_date
)

You can also phrase this as:

students_admission.admission_date = coalesce(:admission_date, students_admission.admission_date)

Note that you should be use parameterized queries rather than mungling string variables into the query string: this is both more efficient and safer (your current code is widely exposed to SQL injection). See this famous SO post for the whys and hows.

Also, please note that putting conditions on the left joined table in the where clause of the query actually turns the left join to an inner join. You probably want this condition in the on clause of the join instead.

GMB
  • 216,147
  • 25
  • 84
  • 135
  • i declared $admission_date variable on the top. Sometimes, this variable has a value or sometimes this variable is set to null. I don't want to run AND condition when the value of a variable is set to null. – Naina Apr 20 '20 at 11:13