2014-11-21 58 views
3

我有一個表中,我得到了我想要的運營商使用的值:使用MySQL行值作爲MySQL的操作

+ 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

可能的重複[在MySQL中評估表達式](http://stackoverflow.com/questions/17046001/evaluate-expression-in-mysql) – 2014-11-21 10:17:50

+0

@OscarPérez...不是 – 2014-11-21 10:24:26

+1

好吧,它幾乎是一樣的......兩個問題都提出了一種評估在數據庫中存儲爲文本的表達式的方法,不是嗎? – 2014-11-21 10:32:01

回答

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 

(未測試,但它應該工作)

1

,不使用的功能,我能想到這樣做會使用3個被聯合查詢的唯一途徑: -

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`