mysql初选条件

如果主条件匹配,返回结果基于主条件,无论二级条件是否匹配,如果没有匹配结果,则返回二级条件的数据库。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

然而,还有没有其他更好的解决办法?

回答:

你可以得到所有相关的行,由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

回答:

尝试使用这个小提琴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)

以上是 mysql初选条件 的全部内容, 来源链接: utcz.com/qa/263958.html

回到顶部