如何使用条件创建Mysql动态查询语句

时间:2018-10-02 08:37:49

标签: mysql sql mybatis

我正在尝试为Mybatis创建具有某些条件的动态查询语句。

这不是有效的查询语句,但这描述了我当前的情况。

SELECT * FROM myTemp WHERE name="Jin" if (
(name is null AND type = 0 ANd status = 2) OR (name is NOT NULL AND 
type = 0 AND status =2 ) );

假定值“ name”是动态值,如果名称不为空(不为null),则执行名称值为

的查询
SELECT * FROM myTemp Where type = 0 AND status = 2 AND name ="someValue"

否则,如果名称为空或null,则执行不带名称值的查询,例如,

SELECT * FROM myTemp where type = 0 AND status = 2.

如何在上述条件下创建MySQL查询语句?

2 个答案:

答案 0 :(得分:1)

You could use COALESCE function to select first non-null value. Like this:

SELECT * FROM myTemp Where type = 0 AND status = 2 AND name = COALESCE("someValue", name)

This way, if you give "someValue", it will be matched to name. If you give NULL instead of "someValue", it will match to name which is always equal.

答案 1 :(得分:0)

Try something like this:

SELECT *
FROM myTemp
WHERE type = 0 AND status = 2 AND (name = "someValue" OR name IS NULL)