2012-03-24 97 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 
相关问题