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:
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.
Thanks in advance
You can assign a variable using SET outside the query, depending on how you receive the user input. Then check the variables inside the query with 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.
You could also make a stored procedure that checks the variables for null before querying. In a stored procedure you can use if conditions for instance.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.