简体   繁体   中英

MySQL SELECT UNION Distinct on single column

I have two tables for storing exchange rates in my system. the first one agent_rate is as follows.

ID  Currency Rate
=======================
3   GBP      0.65
4   EUR      0.70
5   JPY      57.4

the second table exchange_rate is as follows.

ID  Currency Rate
=======================
1   USD         1
2   ZMK       200
3   GBP       0.5
4   EUR      0.75
5   JPY      60.4
6   CHF       0.9

I want to select all the rows in the first table agent_rate and then add all the missing values of ID from the exchange_rate table. I wanted to use a union statement with distinct on a single column but I failed to. My current solution as follows (visual studio)

  1. select from agent_rate table and fill rate datatable
  2. set unique field ie ID in rate datatable
  3. select and fill from exchange_rate table into a temp datatable
  4. move records from temp datatable to rate datatable and ignore errors

the resulting table is(should be) as follows:

ID  Currency Rate
=======================
1   USD         1
2   ZMK       200
3   GBP      0.65
4   EUR      0.70
5   JPY      57.4
6   CHF       0.9

Is there a better way to do this in Sql?

You can join the table and select the agent values first if they exist, otherwise the vaolue from the exchange table

select coalesce(a.id, e.id) as id, 
       coalesce(a.currency, e.currency) as currency,
       coalesce(a.rate, e.rate) as rate
from exchange_rate e
left agent_rate a on a.id = e.id

coalesce returns the first non-null value in the list provided.

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