简体   繁体   English

如何在 where 子句中使用变量?

[英]How can I use a variable inside the where clause?

Let's say that I have four variables named a,b,c,d which I am getting as input from the user and I want to have such query in my application:假设我有四个变量,名为 a,b,c,d 作为用户的输入,我想在我的应用程序中进行这样的查询:

Select * 
from TABLE 
where (TABLE.FIELD = 'a' OR a = null) 
AND (TABLE.FIELD = 'b' OR b = null) ..

Is there a way to bind my variable like this inside the query?有没有办法在查询中像这样绑定我的变量? I am using MySQL and Python.我正在使用 MySQL 和 Python。

Thanks in advance提前致谢

You can assign a variable using SET outside the query, depending on how you receive the user input.您可以在查询之外使用 SET 分配变量,具体取决于您接收用户输入的方式。 Then check the variables inside the query with IS NULL:然后使用 IS NULL 检查查询中的变量:

SET @a := my_val;

SELECT * 
FROM TABLE 
WHERE (TABLE.FIELD = @a OR @a IS NULL)...;

Doing this, in the case where variable a is null, you would get the whole table from the query.这样做,在变量 a 为 null 的情况下,您将从查询中获取整个表。

You could also make a stored procedure that checks the variables for null before querying.您还可以创建一个存储过程,在查询之前检查 null 的变量。 In a stored procedure you can use if conditions for instance.例如,在存储过程中,您可以使用 if 条件。

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

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