我有一张桌子,我在其中获得了我希望用作运算符的值:
+ value 1 + value 2 + operator +
| --------+---------+----------|
| value 1 | value 2 | = |
| value 3 | value 4 | > |
| value 5 | value 6 | < |
+---------+---------+----------+
我想知道是否可以使用operator
列作为WHERE
子句的运算符来编写查询,例如:
SELECT *
FROM table1 table2 operatorTable
WHERE `table1`.`id` `operatorTable`.`operator` `table2`.`id`
此查询中的operatorTable.operator
分别由=
,>
或<
替换。
我的意思是,我知道如何在PHP中完成这一切,但我想严格使用MySQL:)
目标是实现查询的最大速度。
答案 0 :(得分:1)
不使用函数我能想到的唯一方法就是使用3个UNIONed查询: -
SELECT *
FROM table1 table2 operatorTable
WHERE `operatorTable`.`operator` = '='
AND `table1`.`id` = `table2`.`id`
UNION
SELECT *
FROM table1 table2 operatorTable
WHERE `operatorTable`.`operator` = '<'
AND `table1`.`id` < `table2`.`id`
UNION
SELECT *
FROM table1 table2 operatorTable
WHERE `operatorTable`.`operator` = '>'
AND `table1`.`id` > `table2`.`id`
答案 1 :(得分:1)
您可以使用CASE运算符:
SELECT *
FROM table1 table2 operatorTable
WHERE
CASE `operatorTable`.`operator`
when '<' then `table1`.`id` < `table2`.`id`
when '=' then `table1`.`id` = `table2`.`id`
when '>' then `table1`.`id` > `table2`.`id`
END CASE
(未经测试,但应该可以使用)