简体   繁体   English

有条件地管理 php 中的 mysql 查询

[英]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.但是,只有当 $admission_date 不是 null 时,我才想添加AND students_admission.admission_date = 'admission_date'这个条件。 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:只需使用 boolean 逻辑:

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).请注意,您应该使用参数化查询而不是将字符串变量混合到查询字符串中:这既更有效也更安全(您当前的代码广泛暴露于 SQL 注入)。 See this famous SO post for the whys and hows.有关原因和方法,请参阅这篇著名的 SO 帖子

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 .另外,请注意,将条件放在查询的where子句中的left join表上实际上会将left join变为inner join You probably want this condition in the on clause of the join instead.您可能希望在joinon子句中使用此条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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