简体   繁体   中英

MySQL - Selecting row with two columns match from a table. If doesn't exist select row with one column

Table:

country_id           state_id           rate
200                   100                1.1
200                   -1                 5.1

I'm trying to create a prioritized select using two combinations: 1. country_id = 200 and state_id = 100. 2. If given combination doesn't exist get country_id = 200 and state_id = -1 Note: the table is not necessarily going to have both rows, they may exist independently.

Tried to use

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
)

another option I've tried is using UNION as subquery.

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
)

Both work fine only if you have both rows in the table and fails if one of them is missing... any ideas?

The question isn't really clear, but you could do something like this

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`

If the first subquery returns NULL then the second subquery is used

see: http://sqlfiddle.com/#!9/802dc3/3

If the ID of the state -1 will be always lower than the ID for any other state I would go for the solution of adding the -1 condition to the WHERE statement, sort by the state_id field and limiting the results to take the first available:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM