MySQL - 从表中选择具有两列匹配的行。如果不存在则选择一列的行

时间:2017-05-19 04:13:42

标签: mysql sql

表:

country_id           state_id           rate
200                   100                1.1
200                   -1                 5.1

我尝试使用两种组合创建优先选择: 1. country_id = 200,state_id = 100。 2.如果给定的组合不存在,则获取country_id = 200和state_id = -1 注意:表不一定要有两行,它们可以独立存在。

试图使用

SELECT CASE a.rate > 0 THEN a.rate ELSE b.rate AS rate
FROM 
(
    (SELECT * FROM taxes WHERE country_id = 200 and state_id = 100) AS a,
    (SELECT * FROM taxes WHERE country_id = 200 and state_id = -1) AS b
)

我尝试的另一个选项是使用UNION作为子查询。

SELECT CASE b.a_rate > 0 THEN b.a_rate ELSE b.b_rate AS rate
FROM 
(
    (
       SELECT rate AS a_rate FROM taxes WHERE country_id = 200 and state_id = 100
       UNION
       SELECT rate AS b_rate FROM taxes WHERE country_id = 200 and state_id = -1
    ) AS b
)

只有当你在表格中有两行时才能正常工作,如果其中一行丢失,则两者都失败......有什么想法吗?

2 个答案:

答案 0 :(得分:1)

问题不是很清楚,但你可以做这样的事情

select
ifnull(
       (select rate 
       from taxes t1 
       where t1.country_id=200
       and t1.state_id = 100)
       ,(select rate
         from taxes t2
         where t2.country_id=200
         and t2.state_id = -1)
       ) as `rate`

如果第一个子查询返回NULL,则使用第二个子查询

请参阅:http://sqlfiddle.com/#!9/802dc3/3

答案 1 :(得分:1)

如果状态-1的ID总是低于任何其他状态的ID,我会选择将<-1>条件添加到 WHERE 语句的解决方案,按< em> state_id 字段并将结果限制为第一个:

select rate
from taxes t
where country_id = 200 and state_id in (200, -1)
order by state_id desc
limit 1;