因此,我的表中或多或少具有以下列结构:
Name Age Operator
---- --- --------
Jhon 35 >
Michael 30 =
Jess 27 <
基于此,我想进行这样的查询
SELECT * FROM mytable WHERE Name = 'John' AND Age > 40
这显然不会返回任何结果,这很好,但是我的问题是我想使用Jhon的“ Operator”值(在这种情况下为>)来达到该条件。
有可能吗?
谢谢!
答案 0 :(得分:1)
您还可以使用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;
答案 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