MySQL - 如何在where子句中应用以匹配多个值?

时间:2018-03-14 09:53:14

标签: mysql sql where-clause

我有值department=apple, department1=orange, department2=banana, department3=tomato, department4=potato

我如何在下面的SQL where子句中说出这样的内容?

u.department = ifContain(department or department1 or department2 or department3 or department4) 
OR 
...... 
OR u.department4 = ifContain(department or department1 or department2 or department3 or department4)

SQL:

   SELECT 
        u.id, u.username, u.status, callstatus, callername,              
        u.alias as alias,
        u.access1, 
        u.access2             
   FROM 
        sh_av_users u 
   INNER 
        join sh_av_profile p on u.profileid=p.id            
   WHERE 
        u.groups='abcd' and 
        u.xyz='xyz' and 
        (
          u.department='{$anyValueMatchOutOf_departments}'  OR 
          u.department1='{$anyValueMatchOutOf_departments}'  OR 
          u.department2='{$anyValueMatchOutOf_departments}'  OR 
          u.department3='{$anyValueMatchOutOf_departments}'  OR 
          u.department4='{$anyValueMatchOutOf_departments}'
        )

2 个答案:

答案 0 :(得分:2)

我认为你需要IN (value,...) function

简单示例:

   SELECT 
        u.id, u.username, u.status, callstatus, callername,              
        u.alias as alias,
        u.access1, 
        u.access2             
   FROM 
        sh_av_users u 
   INNER 
        join sh_av_profile p on u.profileid=p.id            
   WHERE 
        u.groups='abcd' and 
        u.xyz='xyz' and 
        (
          u.department IN ('banana', 'potato')  OR 
          u.department1 IN ('banana', 'potato')  OR 
          u.department2 IN ('banana', 'potato')  OR 
          u.department3 IN ('banana', 'potato')  OR 
          u.department4 IN ('banana', 'potato')
        )

您甚至可以运行嵌套查询:

   SELECT 
        u.id, u.username, u.status, callstatus, callername,              
        u.alias as alias,
        u.access1, 
        u.access2             
   FROM 
        sh_av_users u 
   WHERE u.department in (select dep from departments where location = 'US')

答案 1 :(得分:-1)

我不确定这是否是您想要的,但您可以使用REGEX之类的。

...
u.department  REGEX 'apple|orange|banana|tomato|potato' OR 
u.department1 REGEX 'apple|orange|banana|tomato|potato' OR 
u.department2 REGEX 'apple|orange|banana|tomato|potato' OR 
u.department3 REGEX 'apple|orange|banana|tomato|potato' OR 
u.department4 REGEX 'apple|orange|banana|tomato|potato'
...

但我没有测试过这个。