2015-09-03 73 views
1

我有一個查詢,我只想使用where條件如果參數不爲空或空字符串。只能使用條件如果字符串參數不爲空或空字符串

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子句。

+0

這些搜索詞來自哪裏?你如何生成這個查詢? –

+1

也許你可以嘗試類似'($ searchTerm!=''AND skills.skillName''searchTerm')''? –

+0

我有一個jQuery的方法,將json數據傳遞給實際調用查詢到數據庫的php文件。 –

回答

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); 

然後,當然,你需要綁定相應的參數給您必須構建查詢?字符

2

你知道這在前端。相應地調整。