mysql条件取决于列值

j9per5c4  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(329)

所以,我的表中或多或少有这样的列结构:

Name     Age   Operator
----     ---   --------
Jhon      35      >
Michael   30      =
Jess      27      <

基于此,我想做一个这样的查询

SELECT * FROM mytable WHERE Name = 'John' AND Age > 40

显然,这不会返回任何结果,这很好,但我的问题是,我想使用jhon的“operator”值(>在本例中)来生成该条件。
有可能吗?
谢谢您!

xzv2uavs

xzv2uavs1#

你也可以使用mysql的 PREPARE 以及 EXECUTE 语句来生成动态sql。

SET @name = 'Jhon';
SET @operator = NULL;
SET @age = 10;

SELECT 
 Operator
INTO 
 @operator
FROM 
 Table1
WHERE
 Name = @name;

SET @SQL = CONCAT(
   "SELECT"
 , " * "
 , " FROM " 
 , " Table1 "
 , " WHERE "
 , "  name = '", @name, "' AND age ", @operator, ' ' , @age
);

SELECT @SQL; # not needed but you can see the generated SQL code which will be executed

PREPARE s FROM @SQL;
EXECUTE s;

请参见演示https://www.db-fiddle.com/f/3z59lxaoy1zxc4kdnctpsr/1

dluptydi

dluptydi2#

你可以这样做:

SELECT

* 

FROM Table1
WHERE Name = 'Jhon'AND CASE 
WHEN Operator = '>' THEN Age > 10
WHEN Operator = '<' THEN Age < 10
WHEN Operator = '=' THEN Age = 10
END

看它在小提琴里现场演奏

相关问题