简体   繁体   中英

Create a view based on two tables with value substitution

I struggle with a query and I am not sure how to do this.

I would like to create a view my_view based on the table original_data_table where each values are substituted by non-null values from the table replacement_data_table whenever an id is specified.

Both original_data_table and replacement_data_table have the same structure but with different values.

I tried to use JOIN in my query but I'm not sure if it's the way to go.

SELECT * FROM original_data_table AS o
LEFT JOIN replacement_data_table AS r
ON o.id = r.id

original_data_table

id         name        value

1          David       10
2          John        20
3          Sarah       30
4          Amy         40

replacement_data_table

id         name        value

1          NULL        50
2          Rick        NULL
4          Emma        60

my_view

id         name        value

1          David       50
2          Rick        20
3          Sarah       30
4          Emma        60

You need COALESCE() to get the right value from the right table:

SELECT o.id,
       COALESCE(r.name, o.name) as name,
       COALESCE(r.value, o.value) as value
FROM original_data_table o LEFT JOIN
     replacement_data_table r
     ON o.id = r.id;

Try this:

SELECT o.id as id, IFNULL(r.name, o.name) as new_name, IFNULL(r.value, o.value) as new_value
FROM original_data_table AS o
LEFT JOIN replacement_data_table AS r
ON o.id = r.id 

Try it use case when

SELECT 
  o.`id`,case when o.`name` <> r.`name` and r.`name` is not null then
      r.`name`
    else o.`name`
  end as name
  ,case when o.`value` <> r.`value` and r.`value` is not null then
      r.`value`
    else o.`value`
  end as value
FROM original_data_table AS o
LEFT JOIN replacement_data_table AS r
  ON o.id = r.id 
order by o.id

SQL Fiddle Demo Link

| id |  name | name |
|----|-------|------|
|  1 | David |   50 |
|  2 |  Rick |   20 |
|  3 | Sarah |   30 |
|  4 |  Emma |   60 |

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