MySQL条件取决于列值

时间:2018-07-17 12:16:49

标签: mysql

因此,我的表中或多或少具有以下列结构:

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

基于此,我想进行这样的查询

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

这显然不会返回任何结果,这很好,但是我的问题是我想使用Jhon的“ Operator”值(在这种情况下为>)来达到该条件。

有可能吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

您还可以使用MySQL的PREPAREEXECUTE语句来创建动态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

答案 1 :(得分:0)

您可以这样做:

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