mysql选择基于主要条件

时间:2017-12-18 14:06:31

标签: mysql

如果主要条件匹配,则无论次要条件是否匹配,返回结果基于初始条件,如果没有匹配结果,则返回基于次要条件的数据。

以汇率外币为例,我有一个汇率表,我需要得到美元的汇率:英镑,如果没有,那么得英镑的汇率:美元。如果两者都有,只返回美元:英镑。

id    origin_currency     target_currency     rate_from     rate_to
1     1                   2                   1             0.75    
2     2                   1                   1             1.34

对于上述数据,查询sql应该只返回第一条记录。

我可以使用以下sql来获得我想要的东西:

select * from exchange_rate 
where origin_currency = 1 and target_currency = 2 
union 
select * from exchange_rate 
where origin_currency = 2 and target_currency = 1 
limit 1

但是,还有其他更好的解决方案吗?

2 个答案:

答案 0 :(得分:1)

尝试使用此小提琴sql_fiddle

SELECT *
FROM currency
WHERE
  (origin_currency, target_currency) =
  (SELECT origin_currency, target_currency FROM currency
   WHERE (origin_currency, target_currency)=(1,2)
           UNION ALL
           SELECT origin_currency, target_currency 
           FROM currency WHERE (origin_currency, target_currency)=(2,1)
           LIMIT 1)

答案 1 :(得分:1)

您可以获取所有相关行,按origin_currency = ? DESC排序并限制行数(或只读取结果中的第一行)。请参阅此SQL Fiddle

SELECT
    *
FROM
    currency
WHERE
    (origin_currency = 1 AND target_currency = 2) OR
    (origin_currency = 2 AND target_currency = 1)
ORDER BY
    origin_currency = 1 DESC
LIMIT
    1