2012-03-24 19 views
0

我想從一個數據庫表中選擇一個值或其反向值,只有一個SQL請求。Mysql選擇一個字段值或其相反(雙)

我previoulsy發佈了一個問題,但現在我有更多的規格,這改變了問題。

我的表中的字段有:id, rate, from_value, to_value, date_modified

這是僞代碼,我想只有一個要求做:

SELECT `rate` if `from_value` = $from_value and `to_value` = $to_value 

OR

SELECT (1/`rate`) if `from_value` = $to_value AND `to_value` = $from_value 

WHERE UNIX_TIMESTAMP('NOW()')-".$expirationTime." < UNIX_TIMESTAMP('`date_modified`')) 

我敢肯定,一個的行存在於表中,所以我只想返回rate的值,並且只有在WHERE子句沒有實現時才返回null。我不希望它爲其他行(沒有條件實現)返回NULL。由於

回答

1

看起來像一個簡單的CASE會做的伎倆:

select 
    case 
     when from_value = $from_value and to_value = $to_value then rate 
     when from_value = $to_value and to_value = $from_value then 1/rate 
    end 
... 

你可能想要一個ELSE在CASE上,如果您的WHERE子句不強制CASE的某個分支匹配。

如果你只是想匹配的一個分支,在上述情況下,然後使用WHERE子句行:

select 
    case 
     when from_value = $from_value and to_value = $to_value then rate 
     when from_value = $to_value and to_value = $from_value then 1/rate 
    end 
where (from_value = $from_value and to_value = $to_value) 
    or (from_value = $to_value and to_value = $from_value) 
+0

是這個作品,謝謝。但是對於其他行,返回NULL,即使ELSE子句沒有被指定爲oO。難道不可能在ELSE中強制返回任何東西嗎? ELSE IGNORE或其他什麼 – student310 2012-03-24 06:01:06

+0

@ student310:你得到NULL是因爲沒有ELSE爲不符合WHEN的行提供值。如果要排除其他行,則使用WHERE子句:'where(from_value = $ from_value和to_value = $ to_value)或(from_value = $ to_value和to_value = $ from_value)''。 – 2012-03-24 06:13:05

+0

非常感謝,這按預期工作。 – student310 2012-03-24 06:51:24

0

沒有嘗試過這一點,但你可以使用IF構造如下

SELECT if from_value = $from_value and to_value = $to_value then rate else 1/rate end as rate from tablename 
相關問題