简体   繁体   English

Mysql if语句在where子句中

[英]MySql if statement in where clause

I have a code that is not working 我的代码无法正常工作

SELECT DISTINCT CONCAT(u.firstname, ' ', u.lastname) AS fnameLname, s.student_number, u.user_id
FROM user u
LEFT OUTER JOIN student s ON u.user_id = s.user_id
WHERE 
case when @filter != ''
then ((u.firstname REGEXP CONCAT('^[', @filter, ']') OR u.lastname REGEXP CONCAT('^[', @filter, ']')) OR student_number REGEXP CONCAT('^[', @filter, ']'))
else 1=1 
AND (u.user_type_id = 0)
ORDER BY u.lastname, u.firstname

I want to select users from table user , I have implement search field (for searching on student_number or on start of firstname and lastname (just first letter of firstname or lastname)). 我想从表user中选择用户 ,我实现了搜索字段(用于搜索student_number或名字和姓氏(仅名字或姓氏的首字母)的开头)。

For example, if I search for "js", it would match for example John Smith, and not John Moses. 例如,如果我搜索“ js”,它将与例如John Smith而不是John Moses相匹配。 It would also match Jeremy Sassone. 它也将匹配杰里米·萨森。 @filter is control parameter in asp.net. @filter是asp.net中的控制参数。

Could anyone help me? 有人可以帮我吗?

You could use and and or for this. 您可以为此使用andor No need for the complicated case when s, and inner case when s, etc.: s case when不需要复杂的case when ,而s case when不需要内部case when ,等等:

where ( ( @filter != '%'
          and ( u.firstname REGEXP CONCAT('^[', @filter, ']')
                or u.lastname REGEXP CONCAT('^[', @filter, ']')
                or student_number REGEXP CONCAT('^[', @filter, ']')
             )
       )
       or @filter = '%'
      )
and   u.user_type_id = 0

The default value for @filter would be '%' - with an empty string it's a syntax error because of the empty square brackets. @filter的默认值为'%'-带有空字符串,这是语法错误,因为方括号为空。

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

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