简体   繁体   中英

Conditionally manage a mysql query in php

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?

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 join ed 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM