mysql SQL查询使用多个条件和LIKE通配符

6yjfywim  于 2023-02-18  发布在  Mysql
关注(0)|答案(2)|浏览(183)

我试图检查所涉及的人名(1,2,3或4)之一是否存在于我的数据库中。我尝试了以下查询,但它不工作,因为我想要的。

SELECT *
FROM db.cases
WHERE (inv_person_name_1 OR inv_person_name_2 OR inv_person_name_3 OR inv_person_name_4) LIKE '%something%'

我也不能用

SELECT *
FROM db.cases
WHERE inv_person_name_1 LIKE '%something%'
      OR inv_person_name_2 LIKE '%something%'
      OR inv_person_name_3 LIKE '%something%'
      OR inv_person_name_4 LIKE '%something%'

因为它不符合我的程序需要。我只需要一个LIKE“%something%”

yhuiod9q

yhuiod9q1#

假设您使用的是C#(当前标记的),则需要使用SqlParameters格式化查询:

SELECT * FROM db.cases 
WHERE inv_person_name_1 LIKE {0} 
OR inv_person_name_2 LIKE {0} 
OR inv_person_name_3 LIKE {0} 
OR inv_person_name_4 LIKE {0};

或:

SELECT * FROM db.cases 
WHERE inv_person_name_1 LIKE @name 
OR inv_person_name_2 LIKE @name 
OR inv_person_name_3 LIKE @name  
OR inv_person_name_4 LIKE @name;

在这种情况下,您需要执行cmd.BindByName = true;(请参见better way of using a single parameter multiple times in c#
另一种方法是丑陋的,但如果您的LIKE将始终是%something%(即通配符之前和之后),您可以这样连接名称:

SELECT * FROM db.cases 
WHERE (inv_person_name_1 || '+' || inv_person_name_2 || '+' || inv_person_name_3 || '+' || inv_person_name_4) LIKE @name;

SELECT * FROM db.cases 
WHERE CONCAT_WS('+', inv_person_name_1, inv_person_name_2, inv_person_name_3, inv_person_name_4) LIKE @name;
qvtsj1bj

qvtsj1bj2#

SELECT * FROM db..cases WHERE inv_person_name IN (1, 2, 3, 4) -- for integer types

SELECT * FROM db..cases WHERE inv_person_name IN ('1', '2', '3', '4') -- for varchar types

相关问题