仅当string参数不为null或空字符串时才使用where条件

时间:2015-09-03 16:56:28

标签: mysql

我有一个查询,我只想使用where条件,如果参数不是null或空字符串。

select
users.user_id,
users.fname,
users.lname,
Certifications.certName,
skills.skillName
from users
left join Certifications on users.user_id = Certifications.user_id
left join specializations on users.user_id = specializations.user_id
left join skills on skills.user_id = skills.user_id
where
(Certifications.certName is not null and Certifications.certName like 'CCNA Routing and Switching')  or 
(skills.skillName is not null and skills.skillName like '') or
(users.location is not null and users.location like '') 
group by users.user_id

因此,如果skillNamelocation的搜索字词为空,我不想在where子句中包含这些字词。

2 个答案:

答案 0 :(得分:2)

你在前端知道这一点。相应调整。

答案 1 :(得分:1)

您必须仅使用非空参数

构建查询
$whereClauses = array();
if (!empty($certifications)) {
   $whereClauses[] = 'Certifications.certName like ?';
}
if (!empty($skillName)) {
   $whereClauses[] = 'skills.skillName like ?';
}
if (!empty($location)) {
   $whereClauses[] = 'users.location like ?';
}
$query .= implode(' OR ', $whereClauses);

那么,当然,你需要将相应的参数绑定到?字符