代码之家  ›  专栏  ›  技术社区  ›  user285594

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

  •  0
  • user285594  · 技术社区  · 6 年前

    我有价值观 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 回复  |  直到 6 年前
        1
  •  1
  •   davidbaumann    6 年前

    我想你需要 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')
    
        2
  •  -1
  •   wayneOS    6 年前

    我不确定这是否是你想要的,但你可以使用 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'
    ...
    

    但我没有测试这个。